Recipe 12.1 Including JavaScript Modules in a Servlet


Problem

You want to import a module or file containing JavaScript code so that the JavaScript can be included in the servlet's HTML output.

Solution

Use the javax.servlet.RequestDispatch.include( ) method to import the needed JavaScript into your page.

Discussion

An efficient method for handling JavaScript throughout a web project is to store the JavaScript code in separate files or modules. Servlets that require the JavaScript functions can then import the JavaScript modules. You would not store your Java class files willy-nilly all over the computer's filesystem without an organization that mirrors the code's purpose. Nor should you organize your JavaScript in anything but well-defined modules.

The JavaScript is included in the servlet's HTML output with script tags and executed in the browser when needed. Example 12-1 shows a module of JavaScript code named functions.js . This module is stored in the web application's WEB-INF/javascript directory.

A sensible place to store JavaScript modules is in their own directory, so that they are easy to locate and do not clutter up the top-level directory of the web application. The JavaScript directory can be a sub-directory of WEB-INF , as in this recipe.


Example 12-1. A JavaScript module
 <script language="JavaScript">  function CheckEmail(email) {     var firstchunk,indx,secondchunk     if (email == ""){         alert("Please make sure you have entered a valid " +             "email before submitting the info.")         return false     }     //get the zero-based index of the "@" character     indx = email.indexOf("@")     //if the string does not contain an @, then return false     if (indx == -1 ){         alert("Please make sure you have entered a valid " +             "email before submitting the info.")         return false     }     //if the first part of email is < two chars and thye second part is < seven chars     //(arbitrary but workable criteria), reject the input address     firstchunk = email.substr(0,indx) //up to but not including the "@"     //start at char following the "@" and include up to end of email addr     secondchunk = email.substr(indx + 1)      //if the part  following the "@" does not include a period "." then     //also return false     if ((firstchunk.length < 2 )  (secondchunk.length < 7)          (secondchunk.indexOf(".") == -1)){          alert("Please make sure you have entered a valid " +             "email before submitting the info.")         return false }     //the email was okay; at least it had a @, more than one username chars,     //more than six chars after the "@", and the substring after the "@"     // contained a "." char     return true }//CheckEmail function CreateWindow(uri) {     var newWin =         window.open(uri,'newwin1',             'width=500,height=400,resizable,' +             'scrollable,scrollbars=yes');     newWin.focus( ); }  </script> 

The module in Example 12-1 contains a script block with two JavaScript function definitions. The function CheckEmail ensures that the email address a user has typed into an HTML form contains at least an @ character, two characters preceding the @ and seven characters after that character, and that the characters after the @ contain a period character (.). The CreateWindow function creates a new browser window with the supplied URI.

Example 12-2 shows a servlet that imports this JavaScript file using the javax.servlet.RequestDispatcher.include( ) method.

Example 12-2. A servlet includes a JavaScript file
 package com.jspservletcookbook;            import javax.servlet.*; import javax.servlet.http.*; public class ModuleServlet 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/functions.js");       dispatcher.include(request, response);  out.println("<title>Client Forms</title></head><body>");       out.println("<h2>Enter Your Name and Email</h2>");  out.println("<form action=           \"/home/displayHeaders.jsp\" name=\"entryForm\" onSubmit=            \" return CheckEmail(this.email.value)\">");  out.println("<table border=\"0\"><tr><td valign=\"top\">");       out.println(           "First and last name: </td>  <td valign=\"top\"><input type=           \"text\" name=\"name\" size=\"20\"></td></tr>");       out.println("<tr><td valign=\"top\">");       out.println("Email: </td>         <td valign=\"top\"><input type=\"text\" name=           \"email\" size=\"20\"></td>");       out.println("<tr><td valign=\"top\"><input type=       \"submit\" value=\"Submit\" ></td>");       out.println("</tr></table></form>");             out.println("</body></html>");      } //doGet } 

The servlet in Example 12-2 uses a RequestDispatcher to include the code contained in functions.js within the HTML head tag generated by the servlet. The generated page includes an HTML form tag. When the page user clicks the Submit button, the form tag's onSubmit event handler checks the email address that the user typed into the form using the imported JavaScript CheckEmail function. This function returns false , which cancels the form submission if the email address does not meet the simple criteria specified by the function.

Figure 12-1 shows what the web page looks like when the user has entered an email address into the form.

Figure 12-1. A servlet generates a web page containing JavaScript
figs/jsjc_1201.gif

Users can also use the built-in src attribute of the HTML script tag to import a JavaScript module, as in:

 <script src="functions.js"> 

See Also

The Netscape DevEdge site at http://devedge.netscape.com/; Recipe 12.2, Recipe 12.4, and Recipe 12.6 on using JavaScript with JSPs; Recipe 12.3 on using JavaScript with servlets for creating new browser windows ; 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

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