Using Scriptlets
The scriptlet
element
can be
used to add a whole block of code to a page, including variable
declarations. The code block must be enclosed by a scriptlet
start-identifier, <%
, and an end-identifier,
%>
. Example 15-1 shows a
scriptlet that creates test data for action elements.
Example 15-1. Scriptlet creating test data (scriptlet.jsp)
<%@ page language="java" contentType="text/html" %>
<%@ page import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%
// Create an ArrayList with test data
ArrayList list = new ArrayList( );
Map author1 = new HashMap( );
author1.put("name", "John Irving");
author1.put("id", new Integer(1));
list.add(author1);
Map author2 = new HashMap( );
author2.put("name", "William Gibson");
author2.put("id", new Integer(2));
list.add(author2);
Map author3 = new HashMap( );
author3.put("name", "Douglas Adams");
author3.put("id", new Integer(3));
list.add(author3);
pageContext.setAttribute("authors", list);
%>
<html>
<head>
<title>Search result: Authors</title>
</head>
<body bgcolor="white">
Here are all authors matching your search critera:
<table>
<th>Name</th>
<th>Id</th>
<c:forEach items="${authors}
" var="current">
<tr>
<td><c:out value="${current.name}" /><td>
<td><c:out value="${current.id}" /><td>
</tr>
</c:forEach>
</table>
</body>
</html>
The scriptlet element contains Java code that creates a
java.util.ArrayList
with
java.util.HashMap
elements and saves the list as a
page scope attribute named authors
by calling ...
Get JavaServer Pages, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.