Java Servlet Forwarding HTTP requests.

Forwarding a client request with a servlet?

  • The HttpServletRequest interface has a method, getRequestDispatcher(), that returns a RequestDispatcher interface, which has a method, forward() to forward the request to another path.
    A Forward example:
    ...
    try 
    {
      request.getRequestDispatcher("/ConfirmationServlet").forward(request, response);
    }
    catch (ServletException e)
    {
      e.printStackTrace();
    }
    ...
  • This will return a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
  • A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response.
  • Forwarding a request as described above only works for other resources (servlets and JSP pages).
  • The pathname specified may be relative, although it cannot extend outside the current servlet context.
  • If the path begins with a "/" it is interpreted as relative to the current context root.
  • This method returns null if the servlet container cannot return a RequestDispatcher.

Example of a simple Servlet Forwarding.

As selected we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletRequestforwarding).

  • A simple Servlet Forwarding example:
    package app.forward;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class MultipleValueFieldHandlerServlet extends HttpServlet
    {
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
      { // gets all the selected options from the client browser form
        String[] selectedOptions = request.getParameterValues("options");
    
        // Do a converting of the selected option
        ArrayList<String> selectedOptionLabels = null;
        if (selectedOptions != null)
        {
          selectedOptionLabels = new ArrayList<String>(selectedOptions.length);
    
          for (String selectedOption : selectedOptions)
          {
            if (selectedOption.equals("option1"))
            {
              selectedOptionLabels.add("Option 1");
            }
            else if (selectedOption.equals("option2"))
            {
              selectedOptionLabels.add("Option 2");
            }
            else if (selectedOption.equals("option3"))
            {
              selectedOptionLabels.add("Option 3");
            }
          }
        }
    // Puts the converted list on a request Attribute
        request.setAttribute("checkedLabels", selectedOptionLabels);
    
        try
        {      
    // Forward the request to /ConfirmationServlet which in
    // the deployment descriptor is defined to be another Servlet, ConfirmationServlet.
          request.getRequestDispatcher("/ConfirmationServlet").forward(request,
              response);
        }
        catch (ServletException e)
        {
          e.printStackTrace();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
    
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is MultipleValueFieldHandlerServlet).

  • The Servlet above will forward the request to a Servlet, ConfirmationServlet.
    This is done by the deployment descriptor (web.xml) in this way:
        <servlet>
            <servlet-name>ConfirmationServlet</servlet-name>
            <servlet-class>app.forward.ConfirmationServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>ConfirmationServlet</servlet-name>
            <url-pattern>/ConfirmationServlet</url-pattern>
        </servlet-mapping>
        
  • The url-pattern, /ConfirmationServlet, inside the servlet-mapping tags refer to the servlet-name ConfirmationServlet that is defined inside the servlet tags to be the servlet-class app.forward.ConfirmationServlet.
    So here is the ConfirmationServlet class:
    package app.forward;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ConfirmationServlet extends HttpServlet
    {
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
      {
        try
        {
          PrintWriter printWriter;
          // gets the list of options from the request Attribute
          // created in the MultipleValueFieldHandlerServlet servlet.
          List<String> checkedLabels = 
                  (List<String>) request.getAttribute("checkedLabels");
          // sets the return data type
          response.setContentType("text/html");
          // gets a Printwriter for returning  responses
          printWriter = response.getWriter();
          printWriter.println("<p>");
          printWriter.print("The following options were selected:");
          printWriter.println("<br/>");
          // returns users (client) selected option
          if (checkedLabels != null)
          {
            for (String optionLabel : checkedLabels)
            {
              printWriter.print(optionLabel);
              printWriter.println("<br/>");
            }
          }
          else
          {
            printWriter.println("None");
          }
          printWriter.println("</p>");
        }
        catch (IOException ioException)
        {
          ioException.printStackTrace();
        }
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is ConfirmationServlet).

  • Please read the comments in the ConfirmationServlet.
    We need a html startup file, multiplevaluedataentry.html, for the browser like this:
    <!DOCTYPE html >
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Multiple Value Submission Demo</title>
      </head>
      <body>
        <form method="post" action="MultipleValueFieldHandlerServlet">
          <p>Please enter one or more options.</p>
          <table >
            <tr>
              <td><input name="options" type="checkbox" value="option1" />
                Option 1</td>
            </tr>
            <tr>
              <td><input name="options" type="checkbox" value="option2" />
                Option 2</td>
            </tr>
            <tr>
              <td><input name="options" type="checkbox" value="option3" />
                Option 3</td>
            </tr>
            <tr>
              <td><input type="submit" value="Submit" /></td>
            </tr>
          </table>
        </form>
      </body>
    </html>

    For those who participate in the review: create a HTML page in Netbeans and replace generated code for the html file with that shown above (the name of the html should be multiplevaluedataentry and places in the folder web).

Creating Deployment descriptor.

  • To run this Servlet you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml. In the later version of java it is possible to specify this in the form of annotations in front of the Servlet.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file regarding servlet, SimpleServlet, should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
        <servlet>
            <servlet-name>MultipleValueFieldHandlerServlet</servlet-name>
            <servlet-class>app.forward.MultipleValueFieldHandlerServlet</servlet-class>
        </servlet>
        <servlet>
            <servlet-name>ConfirmationServlet</servlet-name>
            <servlet-class>app.forward.ConfirmationServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>MultipleValueFieldHandlerServlet</servlet-name>
            <url-pattern>/MultipleValueFieldHandlerServlet</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>ConfirmationServlet</servlet-name>
            <url-pattern>/ConfirmationServlet</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
      <welcome-file-list>
        <welcome-file>multiplevaluedataentry.html</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a Servlet.
  • With a servlet tag we give the Servlet class a servlet name, which is used in the servlet-mapping tag to specify a url for the Servlet.
  • In this way we can have many urls for the same servlet.
  • As shown above, we also need to enter the ConfirmationServlet with mapping information.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file multiplevaluedataentry.html. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ServletRequestforwarding) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/ServletRequestforwarding</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:

    Please enter one or more options.

    Option 1
    Option 2
    Option 3

    Select some of the options and press the submit button.

    The result back to the browser from the Servlet should be something like:
    The following options were selected:
    Option 1
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.