Recipe 12.5 Using JavaScript to Validate Form Values in a Servlet


Problem

You want to validate form input values using JavaScript in a JSP.

Solution

Use a javax.servlet.RequestDispatcher to include the validating JavaScript in the servlet. Then call the validating JavaScript function in the form's onSubmit event handler.

Discussion

Example 12-6 is a JavaScript module named validate.js . This file should be located in WEB-INF/javascript/validate.js . The file contains a script tag that contains one function definition: validate . This JavaScript function iterates through the form elements (such as input tags whose type attribute is text ”in other words, text form fields) to determine if any of them have been left blank. The parameter for the validate function is a form object.

If the user has left the fields empty, this function displays an alert window and then cancels the form submit. A more realistic validation function might involve a greater degree of complex business logic, but I am keeping this example simple in order to demonstrate the mechanics of including the function in a servlet.

Example 12-6. A JavaScript module named validate.js for validating form input
 <script language="JavaScript">  function validate(form1) {     for (i = 0; i < form1.length; i++){        if( (form1.elements[i].value == "")){            alert("You must provide a value for the field named: " +               form1.elements[i].name)            return false            }         }         return true } </script> 

The servlet in Example 12-7 includes the validate.js file using a RequestDispatcher . The RequestDispatcher positions the JavaScript script tag within an HTML head tag in the servlet's output. The servlet page's form tag has an attribute that is composed of the context path (the return value of request.getContextPath( ) ) concatenated with the /displayHeaders.jsp JSP file. If the form fields are filled out properly, the browser submits the form to the JSP page ( /home/displayHeaders.jsp ).

Finally, the form's onSubmit event handler calls the included JavaScript function validate , passing in the this JavaScript keyword. The this parameter evaluates to the form object. If the user fails to fill out the name and email fields, the validate function cancels the browser's submission of the form by returning false .

Example 12-7. Importing JavaScript in a servlet to validate form values
 package com.jspservletcookbook;            import javax.servlet.*; import javax.servlet.http.*; public class FormServlet extends HttpServlet {        public void doGet(HttpServletRequest request,      HttpServletResponse response) throws ServletException,       java.io.IOException {                  response.setContentType("text/html");       java.io.PrintWriter out = response.getWriter( );       out.println("<html><head>");  RequestDispatcher dispatcher = request.getRequestDispatcher(         "/WEB-INF/javascript/validate.js");       dispatcher.include(request, response);  out.println("<title>Help Page</title></head><body>");       out.println("<h2>Please submit your information</h2>");  out.println(         "<form action =\"" + request.getContextPath( ) +             "/displayHeaders.jsp\" onSubmit=\" return validate(this)\">");  out.println("<table border=\"0\"><tr><td valign=\"top\">");       out.println("Your name: </td>  <td valign=\"top\">");       out.println("<input type=\"text\" name=\"username\" size=\"20\">");       out.println("</td></tr><tr><td valign=\"top\">");       out.println("Your email: </td>  <td valign=\"top\">");       out.println("<input type=\"text\" name=\"email\" size=\"20\">");       out.println("</td></tr><tr><td valign=\"top\">");       out.println(         "<input type=\"submit\" value=\"Submit Info\"></td></tr>");       out.println("</table></form>");       out.println("</body></html>");      } //doGet } 

Figure 12-4 shows the browser page containing the form. Figure 12-5 shows the alert window generated by the JavaScript function.

Figure 12-4. The servlet output for an HTML form
figs/jsjc_1204.gif
Figure 12-5. The included JavaScript validate function produces an alert window
figs/jsjc_1205.gif

Another option for validating form input is to use a filter to check parameter values, and then return the user to the form page or a new page if the input contains an error. Developers might prefer this option because a filter allows you to use Java code to parse the parameter values and gives you a great deal of control over the customization of the response page, in the case of a form input error. Recipe 18.3 describes how to use a filter with a servlet to deal with client requests .

See Also

The Netscape DevEdge site at http://devedge.netscape.com/; Recipe 12.2 and Recipe 12.6 on using JavaScript with JSPs to import JavaScript and validate form input; Recipe 12.3 on creating new browser windows with servlets and JavaScript; Recipe 12.5 on validating form values with a servlet and JavaScript; Recipe 18.3 on using a filter with HTTP requests.



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