O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.2. Handling a POST HTTP Request in a JSP

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}" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required