Metawerx Java Hosting Small Logo

Java Scriptlet

A scriptlet is a section of Java code embedded in a JSP page.

JSP consists of JSP tags, HTML, and scriptlets. The JSP compiler converts all of this into a Java Servlet. Scriptlet code is included as-is in the final servlet.

Scriplets are considered messy in a JSP page, as their functionality is often better moved to a JSP Tag File or JSP Custom Tag Library. However, they do have their place, such as in the simple example below.

Example:

<%page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%page import="com.metawerx.util.toolkit.*" %>
<%taglib prefix="tags" tagdir="/WEB-INF/tags" %>

<html>
<body>

    <h1>My test page</h1>
    <tags:test>This is an example of JSP tag</tags:test>

    <%-- JSP comment --%>
    <!-- HTML comment -->

    <%-- Output some info using Java --%>
    <%
        // This is a Java scriptlet, embedded in a JSP page
        out.println("<p />You can use any normal Java here");
        out.println("<p />out - JSPWriter for outputting page text");
        out.println("<p />request - HttpRequest object");
        out.println("<p />This server is: "+request.getServerName());
    %>

</body>
</html>

How to write a scriptlet

  • In standard JSP, a scriptlet begins with <% and ends with %>
  • In XML format JSP, a scriptlet is placed between <jsp:scriptlet> and </jsp:scriptlet> tags


Someone has attached a JSP file called newreport.jsp (see the Attachments section below). This contains an example of scriplets used in a JSP page, mixed with HTML, normal JSP, and JavaScript.

--NealeRudd, 12-Dec-2006

Attachments

newreport.jsp Info on newreport.jsp 6514 bytes
navigation
metawerx specific
search
Share
tools
help

referring pages

Share