O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.3. Creating a New Window with JavaScript in a Servlet

Problem

You want a servlet to contain JavaScript that can generate a new browser window.

Solution

Use a javax.servlet.RequestDispatcher to include the JavaScript function in the servlet. The JavaScript function calls the JavaScript window object's open method.

Discussion

This recipe uses the same imported module as the first two recipes, but this time the servlet uses the second function definition (CreateWindow) rather than the first. Example 12-4 generates an HTML button widget. When the user clicks the button, JavaScript generates a small window (sometimes referred to as a windoid , or pop up). The servlet dynamically retrieves the URL for loading into the new window from a servlet init parameter, which is something you cannot do with a static HTML page.

Example 12-4. A servlet that loads JavaScript for creating a window

package com.jspservletcookbook;           

import javax.servlet.*;
import javax.servlet.http.*;

public class WindowServlet extends HttpServlet {
    
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws 
  ServletException, java.io.IOException {//URL for the pop-up window is configured
     String url = getInitParameter("popup-url");
     
    //just in case the initParameter is misconfigured

     if (url == null || url.equals(""))
         url = "/displayHeaders.jsp";     

     //add the context path as a prefix to the URL, as in /home
     url = request.getContextPath( ) + url; response.setContentType("text/html"); java.io.PrintWriter ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required