O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.8. Using URL Rewriting in a Servlet

Problem

You want to create a servlet that uses URL rewriting if the user has disabled cookies in his browser.

Solution

Use the HttpServletResponse.encodeURL(String url) method to encode all URLs that are used to link with other pages.

Discussion

The javax.servlet.HttpServletResponse class includes a nifty method that will encode a URL with the current session ID, in the event that the user making the servlet request has disabled cookies.

In fact, if you use the HttpServletResponse.encodeURL(String url) method to encode the URLs that are used in a servlet, this method takes care of URL rewriting if necessary, and you won't have to worry about whether cookies are enabled in users' browsers. You must conscientiously encode every URL link involved with the servlet when using this method. Example 11-13 is a servlet version of the example used in Recipe 11.6.

Example 11-13. Using URL rewriting in a servlet

import javax.servlet.*;
import javax.servlet.http.*;

public class UrlRewrite extends HttpServlet {
  
 public void doGet(HttpServletRequest request, 
   HttpServletResponse response)
    throws ServletException, java.io.IOException {
        
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter( );

        String contextPath = request.getContextPath( );String encodedUrl =  response.encodeURL(contextPath +
        "/default.jsp"); out.println("<html>"); out.println("<head>"); out.println("<title>URL Rewriter</title>"); out.println("</head>"); out.println("<body>"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required