Recipe 12.2 Including JavaScript Modules in a JSP


Problem

You want to include a module or file containing JavaScript code within a JSP page's output.

Solution

Use the c:import JSTL core tag.

Discussion

The previous recipe described how to include a file containing JavaScript (Example 12-1) into a servlet's HTML input. It is very easy to accomplish the same task in a JSP, such as by using the importMod.jsp file shown in Example 12-3. This JSP uses the JSTL core tag c:import to include a file named functions.js . The functions.js module contains a script tag with two JavaScript function definitions (Example 12-1 in Recipe 12.1). The HTML generated by the JSP shows that the c:import action positioned the script tag within the JSP's head tag. The JSP generates the HTML form shown previously in Figure 12-1.

Example 12-3. Using the JSTL c:import tag to import JavaScript
  <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>  <html> <head>  <c:import url="/WEB-INF/javascript/functions.js" />  <title>Client Forms</title></head><body> <h2>Enter Your Name and Email</h2>  <form action="/home/displayHeaders.jsp" name="entryForm"         onSubmit="return CheckEmail(this.email.value)">  <table border="0"><tr><td valign="top"> First and last name: </td>  <td valign="top"><input type="text" name="name" size="20"></ td></tr> <tr><td valign="top"> Email: </td>  <td valign="top"><input type="text" name="email" size="20"></td></tr> <tr><td valign="top"><input type="submit" value="Submit"></td> </tr></table> </form> </body></html> 

When the user submits the HTML form, her action is intercepted by the form tag's onSubmit event handler, which does a basic syntax check on the email address the user typed into the form. The form submit, targeted to a /home/ displayHeaders.jsp page, is cancelled if the submitted email address has the wrong syntax.

The JavaScript code this.email.value returns the String that the user typed into the text field named email . The keyword this refers to the form object, which contains the event handler onSubmit . The JavaScript code is a parameter of this event handler.


See Also

The Netscape DevEdge site at http://devedge.netscape.com/; Recipe 12.4 on using JavaScript to create a new window in a JSP; Recipe 12.6 on using JavaScript to validate form input in a JSP; 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

Similar book on Amazon

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