Recipe 23.10 Accessing Request Parameters with the EL


Problem

You want to access a request parameter using the EL in a JSP.

Solution

Use the param implicit object in your JSP code.

Discussion

The JSTL provides an implicit object named param that you can use to get a request parameter. Simply follow the term "param" with a period and the parameter name . Use this terminology with the EL to output the value of a request parameter with the c:out tag. Example 23-11 displays a greeting with the visitor's name. The request might look like:

 http://localhost:8080/home/welcome.jsp?name=Bruce%20Perry 

If the URL does not include the "name" parameter, the JSP displays the message "Hello Esteemed Visitor."

Example 23-11. Using the JSTL in a JSP to display the result of a request parameter
  <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>  <html> <head><title>Accessing a Scoped Value</title></head> <body> <h2>Hello  <c:choose> <c:when test="${empty param.name}">  Esteemed Visitor  </c:when> <c:otherwise> <c:out value="${param.name}" /> </c:otherwise> </c:choose>  </h2> </body> </html> 

The code tests whether the request contains a value for name by using the empty EL keyword:

 <c:when test="${empty param.name}"> 

The c:choose , c:when , and c:otherwise tags are like if/then/else statements in Java code. If the request parameter name does not have a value, the browser will display "Esteemed Visitor". Otherwise, it displays the value of name .

Figure 23-6 shows a JSP displaying the message, including the parameter value.

Figure 23-6. Humble output of a JSP using the param JSTL implicit object
figs/jsjc_2306.gif

See Also

Chapter 18 on working with the client request; the Jakarta Project's Taglibs site: http://jakarta.apache.org/ taglibs /index.html; Sun Microsystem's JSTL information page: http://java.sun.com/products/jsp/jstl/; Recipe 23.3 on using the core tags; Recipe 23.4 and Recipe 23.5 on using the XML tags; Recipe 23.6 on using the formatting tags; Recipe 23.7 and Recipe 23.8 on using the SQL JSTL tags; Recipe 23.11-Recipe 23.14 on using the EL to access request headers, cookies, and JavaBean properties.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net