URL Rewriting
If your browser does not support cookies, URL rewriting provides you with another session tracking alternative. URL rewriting is a method in which the requested URL is modified to include a session ID. There are several ways to perform URL rewriting. You are going to look at one method that is provided by the Servlet API. Listing 5.3 shows an example of URL rewriting.
Listing 5.3 URLRewritingServlet.java
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class URLRewritingServlet extends HttpServlet { //Initialize global variables public void init(ServletConfig config) throws ServletException { super.init(config); } //Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>URL Rewriting</title></head>"); out.println("<body>"); // Encode a URL string with the session id appended // to it. String url = response.encodeRedirectURL( "http://localhost:8000/servlet/checkout?sid=5748"); // Redirect the client to the new URL response.sendRedirect(url); out.println("</body></html>"); out.close(); } //Get Servlet information public String getServletInfo() { return "URLRewritingServlet Information"; } }
This servlet services a GET request and redirects the client to a new URL. This new URL has the string sid=5748 appended to it. This string represents a session ID. When the servlet that services the redirection receives the request, it will be able to determine the current user based on the appended value. At that point, the servlet can perform a database lookup on the user and her actions based on this ID.
Two methods are involved in this redirection. The first is HttpServletResponse.encodeRedirectURL(), which takes a String that represents a redirection URL and encodes it for use in the second method. The second method used is the HttpServletRequest.sendRedirect() method. It takes the String returned from the encodeRedirectString() and sends it back to the client for redirection.
The advantage of URL rewriting over hidden form fields is the capability to include session tracking information without the use of forms. Even with this advantage, it is still a very arduous coding process.