Wednesday, August 8, 2012

Servlet Redirecting


How to do Redirecting?

  • The HttpServletReponse interface has a method, sendRedirect(), that sends the response to another path.
    A Redirect example:
    ...
    // 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.
    A simple Servlet Redirect program:
    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.");
        }
      }
    }
    
    How to try examples.
  • 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:
        <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 colspan="2"><input type="submit" value="Submit" /></td>
            </tr>
          </table>
        </form>
        
    How to try examples.
    The form will look like:

  • When the user press the submit button he will be redirected to selected option url.
  • All source code examples in this session is part of a complete example, ServletResponseRedirect, that you can download.

No comments:

Post a Comment