Java Servlet Redirecting HTTP responses

Servlet Redirecting HTTP response

  • The HttpServletReponse interface has a method, sendRedirect(), that sends the response to another path.
    How to do this:
    ...
    // If the request has a parameter, searchEngine, we sends a Redirect
    // to the url value of that parameter. Else we return a message back to the client
    String url = request.getParameter("searchEngine");
    if (url != null) {
      response.sendRedirect(url);
    }
    else {
      PrintWriter printWriter = response.getWriter();
      printWriter.println("No search engine was selected.");
    }
    ...
  • This method can accept relative URLs.
  • The servlet container must convert the relative URL to an absolute URL before sending the response to the client.
  • If the location is relative without a leading '/' the container interprets it as relative to the current request URI.
  • If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.

Example of Servlet handling redirecting.

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 ServletResponseRedirect).

  • Servlet handling Redirecting example:
    package app.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ResponseRedirectionServlet extends HttpServlet
    {
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws IOException
      {
        String url = request.getParameter("searchEngine");
    
        if (url != null)
        {
          response.sendRedirect(url);
        }
        else
        {
          PrintWriter printWriter = response.getWriter();
    
          printWriter.println("No search engine was selected.");
        }
      }
    }

    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 ResponseRedirectionServlet).

  • The Servlet above will redirect the request to a url, given as a request parameter, using the response sendRedirect() method.
    The html startup file, index.html, for the browser can be like this:
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Response Redirection Demo</title>
      </head>
      <body>
        <form method="post" action="ResponseRedirectionServlet">
          Please indicate your favorite search engine.
          <table>
            <tr>
              <td><input type="radio" name="searchEngine"
                         value="http://www.google.com">Google</td>
            </tr>
            <tr>
              <td><input type="radio" name="searchEngine"
                         value="http://www.msn.com">MSN</td>
            </tr>
            <tr>
              <td><input type="radio" name="searchEngine"
                         value="http://www.yahoo.com">Yahoo!</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 index 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, ResponseRedirectionServlet, should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <servlet>
        <servlet-name>ResponseRedirectionServlet</servlet-name>
        <servlet-class>app.servlet.ResponseRedirectionServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>ResponseRedirectionServlet</servlet-name>
        <url-pattern>/ResponseRedirectionServlet</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
                30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>index.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.
  • 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 index.html. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

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

    For those who participate in the review: create a Glassfish 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>/ServletResponseRedirect</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 indicate your favorite search engine.
    Google
    MSN
    Yahoo!
    When the user press the submit button he will be redirected to selected option url.
© 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.