JSP Scriptlet Tag with Example

A scriptlet is a set of Java programming statements embedded in an HTML page.
All JSP Examples at JSP Source Code Examples

JSP Scriptlet Syntax

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 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:
All JSP Examples at JSP Source Code Examples

Comments