Recipe 12.4 Creating a New Window with JavaScript in a JSP


You want to use JavaScript in a JSP to create a new browser window.


Use the c:import JSTL tag to import the JavaScript code into the JSP. Then use the initParam JSTL implicit object to dynamically provide the URL for a JavaScript-generated window.


The JSP in Example 12-5 ( windowJ.jsp ) uses the JSTL's c:import core tag to import the JavaScript function definition for creating a new window. The JSP then calls the JavaScript function ( CreateWindow ) in the onClick event handler for a web page button. The CreateWindow function loads the URL specified in its parameter into the new browser window. Example 12-5 uses the c:out core tag and EL syntax to dynamically acquire the URL for the JavaScript window from a context parameter. The c:out tag looks like this:

 <c:out value= "${pageContext.request.contextPath}${initParam[\"jsp-url\"]}"/> 

The value attribute specifies two EL expressions. The first one provides the JSP's context path , while the second gives the value of the context-param element jsp-url . The full URL specified by these concatenated EL expressions is /home/cookieReader.jsp .

Example 12-5. Using the JSTL to import JavaScript into a JSP
  <%@ taglib uri="" prefix="c" %>  <html> <head>  <c:import url="/WEB-INF/javascript/functions.js" />  <title>Help Page</title></head><body> <h2>Cookie Info</h2> <form action ="" onSubmit=" return false"> <table border="0"><tr><td valign="top"> Click on the button to get more info on cookies: </td>   <td valign="top">  <input type="button" name="button1" value=     "More Info" onClick= "CreateWindow('<c:out value=     "${pageContext.request.contextPath}${initParam[\"jsp-url\"]}"/>')">  </td></tr> </table></form> </body></html> 

This JSP uses the following context-param element in web.xml :

 <context-param>     <param-name>jsp-url</param-name>     <param-value>/cookieReader.jsp</param-value> </context-param> 

The EL implicit object initParam evaluates to a java.util.Map containing the names and values of any context-param elements configured for the web application. An implicit object is a variable that the JSTL automatically makes available to your JSP code.

Example 12-5 uses the EL syntax initParam[\"jsp-url\"] , as opposed to initParam.jsp-url , in order to return the intended value in Tomcat 5 (alpha version as of this writing). The code's purpose is to escape the hyphen character (-) in "jsp-url."

See Also

The Netscape DevEdge site at; 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 © 2008-2017.
If you may any questions please contact us: