[ Team LiB ] |
![]() ![]() |
Recipe 12.2 Including JavaScript Modules in a JSPProblemYou want to include a module or file containing JavaScript code within a JSP page's output. SolutionUse the c:import JSTL core tag. DiscussionThe 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.
See AlsoThe 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. ![]() |
[ Team LiB ] |
![]() ![]() |