How to redirect a servlet request to another URL

How To Redirect A Servlet Request To Another URL

Date: 25/03/2004

This document will help you to understand:
• How to redirect a servlet request to another URL
• How to run the sample servlet applications

Table of Contents

Introduction
Prerequisites
Software Requirements
How To Redirect A Servlet Request To Another URL
Running the Sample Servlet Applications
Useful References

Introduction

Servlets provide a component-based platform-independent method for building web-based applications, and are generally used to generate dynamic web content. To put it simply, a servlet receives a request from a client (the web browser, for instance), processes the request, and returns the response to the client. For example, the response can be a queried from a database that is displayed using HTML.

For more information about Servlets, refer to the Useful References section later in this document.

What is a Servlet Request Redirection?

At times, outdated/old URLs need to be redirected to new ones so that the user does not see an error when the URL is accessed. In such situations, the URL redirection option allows us to forward the request of that URL to the new location.

There are several instances in which the URL, through which the application is accessed, needs to be changed:

  • When the document moves to a new URL
  • When the application is enhanced to include more pages, like an error page or extra information pages
  • When the user accesses a servlet, differing from the order of the transaction, for example, when the user goes to the final order page before filling out the requisite order details
  • When the servlet requests are distributed to other servers for load balancing.

    In all such cases, the application can make use of different URL redirection techniques that suit the application's behavior.

How can a Servlet Request be Redirected to another URL?

URL redirection can be achieved by using:

  • The forward method of the javax.servlet.RequestDispatcher interface
  • The sendRedirect method of the javax.servlet.http.HttpServletResponse interface
  • The header properties of a few popular browsers

Prerequisites

To work your way through this HowTo, it is necessary to have a basic understanding of the fundamental concepts of servlets, and how to develop and deploy them to a web server.

Software Requirements

  • Oracle10g JDeveloper 9.0.3 or later ( JDeveloper is Oracle's Visual Java Development Tool and can be downloaded from here)
    OR
    - Oracle9AS Container for J2EE(OC4J) 9.0.3 or later (Download from here
  • JDK1.3.x or later. (Download from here.)

How to Redirect a Servlet Request to another URL

As mentioned earlier, there are three different techniques of URL redirection:

  • Redirection using javax.servlet.RequestDispatcher interface methods
  • Redirection using sendRedirect method of the javax.servlet.http.HttpServletResponse interface
  • Redirection by setting the HTTP Response Header's Refresh field

Next we'll look at each of these techniques in some detail.

Redirection using javax.servlet.RequestDispatcher Interface

The javax.servlet.RequestDispatcher object can be obtained from:

      1. A javax.servlet.ServletContext interface - a string containing the relative path to the new resource can be passed to the RequestDispatcher object to redirect the original request to a new one
      2. A javax.servlet.ServletRequest interface - a string containing the relative path to the new resource can be passed to the RequestDispatcher object to redirect the original request to a new one
      3. The getNamedDispatcher method of the javax.servlet.ServletContext interface - a string containing the name of the new resource can be passed to the NamedDispatcher object to redirect the original request to a new one

        Let's now look at each of these methods in some detail.

      1. From a javax.servlet.ServletContext Interface

          ......
          
          public void service(HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException  {
        ........
              // Redirect the request to a new location - redirected.jsp page.  
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/redirected.jsp");
        rd.forward(request, response);

          }                     
          ......             


      2. From a javax.servlet.ServletRequest Interface

          ......
          
          public void service(HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException  {
        ........
              // Redirect the request to a new location - redirected.jsp page.  
        RequestDispatcher rd =request.getRequestDispatcher("/redirected.jsp");
        rd.forward(request, response);

          }                     
          ......             


      3. From the getNamedDispatcher Method of the javax.servlet.ServletContext Interface
        The new location, Servlets/JSP needs to be registered within the web application deployment descriptor, that is, in the web.xml file.

          ......
          
          public void service(HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException  {
        ........
              // Redirect the request to a new location - redirected
        // 'redirected' is the class generated for the JSP file called redirected.jsp  
        RequestDispatcher rd =getServletContext().getNamedDispatcher("redirected");
        rd.forward(request, response);

          }                     
          ......             
        ......

        web.xml mapping:
        <web-app>
        .......
        <servlet>
        <servlet-name>redirected</servlet-name>
        <jsp-file>/redirected.jsp</jsp-file>
        </servlet>
        ......
        </web-app>


    Redirection using the sendRedirect Method of the javax.servlet.http.HttpServletResponse Interface
    In this method, the browser redirects the request to the URL specified. The resource can be a totally different URL or a JSP/Servlet file. Further, the method can accept absolute or relative URLs.

      ......
      
      public void service(HttpServletRequest request,
    HttpServletResponse response)
        throws ServletException, IOException  {
    ........
          // Redirect the request to a new location - http://www.oracle.com  
    response.sendRedirect("http://www.oracle.com");

      }                     
      ......             

    Redirection by Setting the HTTP Response Header's Refresh Field
    The header must be set before sending the response body. This method is useful if it's needed to display a message before redirecting the client to a different URL. The delay in seconds can be set in the header properties that actually redirects the request to go to the new URL in specified number of seconds. Following is the code snippet:

    res.setHeader("Refresh", wait in seconds + "; URL=" + new location);

    Note that this header is not officially part of HTTP 1.1. This extension, however, is supported by both Netscape and Internet Explorer.

      ......
      
      public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException  {
    ........
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // set the content type
    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    // Instruct the browser to wait 5 seconds before redirecting to a new URL
    // Here two ways are shown. It can be directed to a different URL altogether
    // or can also be directed to a servlet/JSP within the application.
    String mesg = "Hi!";

    response.setHeader("Refresh", "5; URL=http://www.oracle.com");
    //response.setHeader("Refresh", "5; URL=../redirected.jsp?param1="+mesg);

    // output a message that notifies the user that the
    // browser is going to be redirected to a new page
    out.println("<HTML>");
    out.println("<BODY>");
    out.println("The page you requested is moved to a different location. ");
    out.println("Your browser will automatically take you<BR>");
    out.println("to the new location in 5 seconds.<BR>");
    out.println("If the browser does not take you to the new location, ");
    out.println("or you don't want to wait then,");
    out.println(" <a href=\"../redirected.jsp?param1="+mesg+"\">Click Here</a><BR>");
    out.println("</BODY>");
    out.println("</HTML>");
      }                     
      ......             

Running the Sample Servlet Application

This section talks about how to get the servlets up and running. The application downloadable Jar file has a set of three servlet applications that demonstrate different redirection techniques.

Running the Servlet Sample Application in OC4J (EAR Deployment):

    The sample application ServletURLRedirection.jar can be downloaded from here. The Jar file extracts all the sample application files to a folder called ServletURLRedirection. Go through the following steps to deploy and run the servlet in OC4J. 

    1. Add servlet.jar to the CLASSPATH; this file is present under <OC4J_HOME>/j2ee/home/lib folder.
      Note: <OC4J_HOME> is the folder where the OC4J server is installed; for example, d:\oc4j
    2. From the ServletURLRedirection folder, compile the servlet files: Servlet1.java, UsingHeaderRedirection.java, UsingRequestDispatcher.java, UsingSendRedirect.java using the following command:
      javac src/oracle/otnsamples/servlets/*.java -d ./WEB-INF/classes
      - This creates the classes for the servlet files under the WEB-INF/classes/oracle/otnsamples/servlets folder.
    3. Next, create a WAR file containing all the servlet classes, JSPs, HTML files and the web.xml file using the JAR command:
      jar -cvfM redirection.war WEB-INF/* web/*.jsp web/*.html

    4. Create a EAR file containg the application.xml file and WAR file using the JAR command again.
      jar -cvfM redirection.ear redirection.war META-INF
    5. Start the OC4J server.
    6. Copy the EAR file: redirection.ear to the <OC4J_HOME>/j2ee/home/applications folder.
    7. Deploy the servlet applications using the command below:

      java -jar <OC4J_HOME>/j2ee/home/admin.jar ormi://<server>:<rmiport> admin <admin_password> -deploy -file <Sample_Name>.ear -deploymentName <earDeploymentName>

      Example:
      java -jar D:/oc4j903/j2ee/home/admin.jar ormi://incq207a.idc.oracle.com:23791 admin welcome -deploy -file redirection.ear -deploymentName redirection

      Note:
      <server> is the IP Address of the system where the OC4J instance is running.
      <rmiport> is the RMI port number of the OC4J instance; default is 23791
      <admin_password> is the password of the OC4J installation
      <Sample_Name>.ear is the EAR file created, that is, redirection.ear
      <earDeploymentName> is the deployment name for the application, that is, redirection

    8. Bind the web application to a context root using the following command:

      java -jar <OC4J_HOME>/j2ee/home/admin.jar ormi://<server>:<rmiport> <admin_username> <admin_password> -bindWebApp <earDeploymentName> <Sample_War_Name> http-web-site /<website_root>

      Example: java -jar D:/oc4j903/j2ee/home/admin.jar ormi://incq207a.idc.oracle.com:23791 admin welcome -bindWebApp redirection redirection http-web-site /redirection

    9. Access the servlets using the URLs like this:

      http://localhost:8888/redirection/servlet/UsingRequestDispatcher
      http://localhost:8888/redirection/servlet/UsingSendRedirect
      http://localhost:8888/redirection/servlet/UsingHeaderRedirection
    10. Here localhost is your machine where OC4J instance is running. 8888 is the default port of OC4J.

    11. Each of the servlet thus invoked demonstrate a different redirection technique.

Running the Servlet Sample Application from Oracle JDeveloper9i:

    The sample ServletURLRedirection.jar application can be downloaded from here. The Jar file extracts all the sample application files to ServletURLRedirectionfolder. Go through the following steps to run the servlet from JDeveloper.

    1. From JDeveloper, open the  ServletURLRedirection.jws workspace file. This will open the corresponding project and source files of the application.
    2. Compile the ServletURLRedirection.jpr project.

    3. Click on UsingRequestDispatcher.java and run the servlet. Similarly, you can run the other servlets - UsingSendRedirect and UsingHeaderRedirection
    4. Each of the servlet thus invoked demonstrate a different redirection technique.

Useful References

Do enter your comments about this HowTo in the OTN Sample Code Discussion Forum.


How To Redirect A Servlet Request To Another URL

Please rate this how-to :
Excellent
Good
Average
Below Average
Poor


E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy