Redirects & Request DispatchingS2C Home « Redirects & Request Dispatching

In all the examples on the site, we have seen so far, all the processing required is done within the same servlet. These programs are relatively short of course and are principally to aid learning a particular aspect of servlets. In the real world a situation may arise where we may wish to pass control back to the browser to serve up a different page. Also with dynamic web applications it is usually a requirement to include output generated by one resource in the output stream of another. The servlet API caters for the first of these situations using redirects and for the second using request dispatching.

With redirects we let the browser do the work for us, with request dispatching we pass control to another resource to do the work on the server side. In this lesson we look at both of these mechanisms and the appropriate use of each depending on the outcome required.

RedirectsTop

When we do a servlet redirect we are passing control back to the browser to render the page we are redirecting to. All we need to do in our servlets when we want to redirect is to use the sendRidirect("theNameOfTheURLWeWishToRedirectTo") method with our response object and put in a URL to redirect to. There are many reasons why we may not want to handle the request ourselves such an updated page that we pass control to or a login screen where the user has directly typed in a URL and hasn't gone through authorization.

Before we look at some code there are a few points to remember when using a redirect:

  1. The users will see a different URL in the browser action bar and so are aware that they are being redirected to a new page.
  2. The sendRedirect() method is part of the javax.servlet.http package and so is not available for non-http requests.
  3. You can't use the sendRedirect() method after writing to the response or you will get a java.lang.IllegalStateException exception.
  4. The URL is always a String object and not a URL object as you might expect.

Absolute RedirectsTop

We can use an absolute URL as shown in the code snippet below:


public void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
    ...     
    // See if the user has logged in
    if (userLoggedIn) {   
        // Handle request
        ...
    } else { 
        // Redirect to login page
        resp.sendRirect("https://server2client.com/login.jsp")
    }
}

Relative To Application RedirectTop

We can also use a relative URL and this comes in two variations dependant upon the use of a forward slash or not. The following code snippet shows how the URL is formed when no forward slash is used. If the original request was for a URL called "https://server2client.com/someApp/work.jsp"


public void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
    ...     
    // See if the user has logged in
    if (userLoggedIn) {   
        // Handle request
        ...
    } else { 
        // Redirect to login page
        resp.sendRirect("auth/login.jsp")
    }
}

The container knows that the original request started from the someApp/ directory and because no forward slash was used our redirect URL gets appended to this. So in this case when the container builds the URL relative to the original URL to redirect to it will include both our new path and the original path minus the original servlet/jsp/HTML page we went to. So in this case the new path to redirect to, created by the container is "https://server2client.com/someApp/auth/login.jsp"

Relative To Container Root RedirectTop

The following code snippet shows how the URL is formed when a forward slash is used. If the original request was for a URL called "https://server2client.com/someApp/work.jsp"


public void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
    ...     
    // See if the user has logged in
    if (userLoggedIn) {   
        // Handle request
        ...
    } else { 
        // Redirect to login page
        resp.sendRirect("/auth/login.jsp")
    }
}

Because we used a forward slash the container knows that we want the original request started from the root of the web container. It derives the URL from the root of the original request and the redirect, so in this case the new path to redirect to, created by the container, will be "https://server2client.com/auth/login.jsp"

Request DispatchingTop

Earlier in the section, in the Attributes & Scope lesson, we looked at the different scopes available within a servlet; these being request, session and context. Now we have a clear understanding of when a scope starts and ends it's a good time to talk about request dispatching and how this mechanism works within the request scope.

Unlike redirects where control is passed back to the browser, with request dispatching we pass control to another servlet/jsp/HTML page on the server side.

The two methods within the RequestDispatcher interface are shown in the table below:

Method Declaration Description
void forward(ServletRequest request,
  ServletResponse response)
Forwards a request from a servlet to another servlet/jsp/HTML page on the server.
void include(ServletRequest request,
  ServletResponse response)
Includes the content of another servlet/jsp/HTML page in the response.

The forward() method is the most commonly used of the two RequestDispatcher interface methods and passes total control to the forwarding resource. The include() method passes temporary control to another resource before returning to the resource that did the request dispatch and is used less frequently in the real world.

Use the links in the table above to go to example code of the method in question.

Before we look at some request dispatching code there are a few points to remember when using request dispatching:

  1. The users will NOT see a different URL in the browser action bar and so are unaware that they are having their request dispatched to a new page.
  2. The RequestDispatcher object can be obtained via ServletRequest or ServletContext types.
  3. You can't use request dispatching after writing to the response or you will get a java.lang.IllegalStateException exception.
  4. The URL is always a String object and not a URL object as you might expect.
  5. The URL is relative to the original request and dependant upon usage of the ServletRequest or ServletContext type different rules apply as explained within the sections below.

Request Dispatching Via The ServletRequest TypeTop

There are two ways we can get a RequestDispatcher, first via the ServletRequest type:


public void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
    ...     
    // See if the user has logged in
    if (userLoggedIn) {   
        // Handle request
        ...
    } else { 
        // Get RequestDispatcher
        RequestDispatcher somePage = req.getRequestDispatcher("login.jsp")   
        // Forward to login page
        somePage.forward(req, resp) 
        // You could also do an include to login page (but never both)
        // somePage.include(req, resp)
    }
}

The rules for relative URLs are the same as for redirects, so with no forward slash the URL is relative to the web app path, with a forward slash the URL is relative to the container root.

Request Dispatching Via The ServletContext TypeTop

We can also do request dispatching via the ServletContext type:


public void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
    ...     
    // See if the user has logged in
    if (userLoggedIn) {   
        // Handle request
        ...
    } else { 
        // Get RequestDispatcher
        RequestDispatcher somePage = getServletContext().getRequestDispatcher("/login.jsp")   
        // Forward to login page
        somePage.forward(req, resp) 
        // You could also do an include to login page (but never both)
        // somePage.include(req, resp)
    }
}

When using the RequestDispatcher derived from the ServletContext type this will always be relative to the container root and so must start with a forward slash.

Lesson 7 Complete

In this lesson we learnt about Redirects and Request Dispatching and how to use these mechanisms.

What's Next?

That's if for the Servlets Intermediate lessons. In the next section we start our look at advanced topics with a look at context listeners.

go to home page Homepage go to top of page Top