Java Servlet & JSP Cookbook

Problem

You want to have a JSP handle the data posted from a form or client application.

Solution

Use the JSTL c:forEach tag to iterate over the parameter names and values.

Discussion

The JSTL makes it very easy to process input data from a POST method. The JSP in Example 7-3 uses only template text and JSTL tags to display posted information. The c:forEach tag iterates over the posted data using the implicit JSTL object param . The param object contains java.util.Map.Entry types, which each hold a key/value pair. The key and value correspond to the name of a submitted parameter and its value, such as "department=Development." Using the Expression Language (EL), the syntax "${map_entry.key}" or "${map_entry.value}" is the equivalent of calling the Map.Entry.getKey( ) and getValue( ) methods . The return values of these method calls are fed to the c:out JSTL tag for display in the HTML page. Figure 7-2 shows what the browser page looks like if the form submitted to the JSP is the one detailed in Example 7-1. With your taglib , use a uri value of http://java.sun.com/jsp/jstl/ core for JSTL 1.1.

Example 7-3. Iterating posted data with the JSTL

<%@page contentType="text/html"%> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html> <head><title>Post Data Viewer</title></head> <body> <h2>Here is your posted data</h2> <c:forEach var="map_entry" items="${param}"> <strong><c:out value="${map_entry.key}" /></strong>: <c:out value="${map_entry.value}" /><br><br> </c:forEach> </body> </html>

Make sure to include the taglib directive when you are using the JSTL tags. The taglib in Example 7-3 takes care of any of the custom tags with the "c" prefix, as in c:forEach .

Chapter 23 explains how to install the JSTL in your web application, make different custom tags, and use the EL.

Figure 7-2. A JSP displaying posted name/value pairs

If you want to get the values of parameters without using a c:forEach tag, then use the code fragment in Example 7-4. This code displays the values of parameters when the parameter names are known by the developer (which is usually the case).

Example 7-4. Displaying individual parameter values using c:out

<h2>Here is your posted data</h2> <strong>User name:</strong>: <c:out value="${param.username}"/> <br><br> <strong>Department:</strong>: <c:out value="${param.department}"/> <strong>Email:</strong>: <c:out value="${param.email}"/>

Substituting this code into the JSP produces the same results as those shown Figure 7-2.

The JSP 2.0 specification is designed to allow the use of the EL in template text ”in other words, without the c:out JSTL tag.

See Also

Recipe 7.2 on handling a POST request in a JSP; Recipe 7.3 on setting the properties of a JavaBean to form input; Recipe 7.4 on setting a scoped attribute to the value of a parameter; Recipe 7.6 on posting data from a JSP; Chapter 23 on using the JSTL.

Категории