JSP Scriptlets

This article is a series of JSP Tutorial. In this article, we will learn what is JSP scriptlet and how to use scriptlet tag with an example.

A scriptlet is a set of Java programming statements embedded in an HTML page. The statements are distinguished from their surrounding HTML by being placed between <% and %> markers, as the following shows:
<% statement; [statement; …] %>
Whitespace is permitted after the <% and before the %>, so the previous scriptlet could also be written as:
<%
statement;
[statement; …]
%>
JSP container moves the statements enclosed in it to _jspService() method while generating servlet from JSP. The reason for copying this code to service method is: For each client’s request the _jspService() method gets invoked, hence the code inside it executes for every request made by a client.

JSP Scriptlet Example

Here is an example of a JSP page that uses a scriptlet to generate a table of ASCII characters:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <H3>ASCII Table</H3>
    <TABLE BORDER="1">
    <%
         StringBuffer sb = new StringBuffer();
         sb.append("<TR>");
         sb.append("<TH WIDTH=40>&nbsp;</TH>");
             for (int col = 0; col < 16; col++) {
                 sb.append("<TH>");
                 sb.append(Integer.toHexString(col));
                 sb.append("</TH>");
             }
                 sb.append("</TR>");
             for (int row = 0; row < 16; row++) {
                 sb.append("<TR>");
                 sb.append("<TH>");
                 sb.append(Integer.toHexString(row));
                 sb.append("</TH>");
                 for (int col = 0; col < 16; col++) {
                     char c = (char) (row * 16 + col);
                     sb.append("<TD WIDTH=32 ALIGN=CENTER>");
                     sb.append(c);
                     sb.append("</TD>");
                 }
                 sb.append("</TR>");
             }
             out.println(sb);
      %>
 </TABLE>
</body>
</html>
Let's invoke this JSP page from a Web browser, you see the table on a browser:

JSP Scriptlet - Best Practice

  • Minimize the amount of scriptlet code in a JSP
  • Avoid dumping thousands of lines of code in a JSP
  • Refactor this into a separate Java class … make use of MVC

Comments