Recipe 19.9 Checking Form Parameters with a Filter


Problem

You want to use a filter to check the values that a user has entered into a form.

Solution

Use the deployment descriptor to map the filter to the servlet or JSP that is the target of the form.

Discussion

Filters offer an alternative to JavaScript and other server-side languages for checking whether the user has entered valid values into HTML form fields. The filter in this recipe initiates a basic check of the request parameters to determine if they are null or the empty String .

Example 19-13 is a JSP that contains an HTML form. The JSP includes some embedded JSTL tags that fill in the text fields with any correct values if the form is returned to the user for corrections. In most cases, a user fills in the vast majority of the fields correctly, but might make a mistake in one or two of them. You do not want to make him fill out all of the fields again.

Example 19-13. A JSP containing a form for users to fill out
  <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head>     <title>Personal Information</title> </head> <body bgcolor="#ffffff">  <c:if test="${! (empty errorMsg)}"> <font color="red"> <c:out value="${errorMsg}"/> </font> </c:if>  <h2>Please enter your name and email address</h2> <table> <form action="/home/thanks.jsp"> <tr><td valign="top">First name: </td> <td valign="top">  <input type="text" name="first" size="15" value=     '<c:out value="${first}" />'>  </td> <td valign="top">Middle initial: </td> <td valign="top">  <input type="text" name="middle" size="2" value=         '<c:out value="${middle}"/>'>  </td> </tr> <tr> <td valign="top">Last name: </td> <td valign="top">  <input type="text" name="last" size="20" value=     '<c:out value="${last}"/>'>  </td></tr> <tr> <td valign="top">Your email: </td> <td valign="top">  <input type="text" name="email" size="20" value=         '<c:out value="${email}"/>'>  </td></tr> <tr><td valign="top"><input type="submit" value="Submit"> </td> <td></td></tr> </form> </table> </body> </html> 

When the user submits Example 19-13, the browser sends the form information to the URL specified in the form tag's action attribute: a JSP page named thanks.jsp . The deployment descriptor maps the filter in Example 19-14 to the URL thanks.jsp . The filter is designed to check the fields' values to determine if the user left any of them blank and, if so, return the user to the form (named form.jsp ).

Make sure to develop all filters with a constructor that does not take any arguments.


Example 19-14. The filter that checks parameters values
 package com.jspservletcookbook; import java.io.IOException;  import java.util.Enumeration;  import javax.servlet.*; import javax.servlet.http.*; public class CheckFilter implements Filter {          private FilterConfig config;        public CheckFilter( ) {}        public void  init(FilterConfig filterConfig)  throws ServletException {       this.config = filterConfig;          }  public void doFilter(ServletRequest request, ServletResponse response,       FilterChain chain) throws IOException, ServletException {              //Get all the parameter names associated with the form fields       Enumeration params = request.getParameterNames( );       boolean rejected = false;              //Cycle through each one of the parameters; if any of them       //are empty, call the 'reject' method          while (params.hasMoreElements( )){                     if (isEmpty( request.getParameter( (String) params.               nextElement( )) ) ){               rejected = true;               reject(request,response);           }//if                  }//while                 //Pass the request to its intended destination, if everything       //is okay       if (! rejected)           chain.doFilter(request,response);            }// doFilter  private boolean isEmpty(String param){              if (param == null  param.length( ) < 1){             return true;         }                  return false;   }  private void reject(ServletRequest request, ServletResponse response)        throws IOException, ServletException {                //Create an error message; store it in a request attribute       request.setAttribute("errorMsg",         "Please make sure to provide a valid value for all of the text "+         "fields.");                Enumeration params = request.getParameterNames( );       String paramN = null;         //Create request attributes that the form-related JSP will       //use to fill in the form fields that have already been       //filled out correctly. Then the user does not have to fill       //in the entire form all over again.       while (params.hasMoreElements( )){             paramN = (String) params.nextElement( );             request.setAttribute(             paramN, request.getParameter(paramN));                 }               //Use a RequestDispatcher to return the user to the form in       //order to fill in the missing values         RequestDispatcher dispatcher = request.        getRequestDispatcher("/form.jsp");        dispatcher.forward(request,response);        }//reject  public void destroy( ){         /*called before the Filter instance is removed          from service by the web container*/   }      } 

The Java comments in Example 19-14 explain what is going on in this filter. Basically, the user is returned to the form, which displays an error message if any of the request parameters are empty. Example 19-15 shows how the CheckFilter is mapped in web.xml . If the user fills in the form correctly, his request is sent to the thanks.jsp page without interuption by the filter.

Example 19-15. The CheckFilter is registered and mapped in web.xml
 <!-- start of web.xml... --> <filter>     <filter-name>CheckFilter</filter-name>     <filter-class>com.jspservletcookbook.CheckFilter</filter-class> </filter> <filter-mapping>     <filter-name>CheckFilter</filter-name>     <url-pattern>/thanks.jsp</url-pattern> </filter-mapping> <!-- rest of web.xml... --> 

Figure 19-3 shows an HTML form that was partially filled out and submitted. The filter sent the form back to the user with a message (in a red font).

Figure 19-3. A filter forwards an error message to a JSP
figs/jsjc_1903.gif

See Also

Chapter 6 on including content using RequestDispatchers ; Recipe 19.8 on using filters with RequestDispatchers ; Recipe 7.9 on using a filter to read request parameter values; Recipe 18.3 on using a filter to alter then forward the request; Recipe 19.1-Recipe 19.4 on mapping filters to web components ; Recipe 19.5 on configuring init parameters for a filter; Recipe 19.6 on blocking a request; Recipe 19.7 on filtering the HTTP response.



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