URL Rewriting in Servlets :-


As we already know, for session tracking web container makes use of cookie (jsessionid). If client browser does not accept the cookies (client disable cookies), URL Rewriting can be used for session tracking.

URL Rewriting takes the session id from cookie and attach it to the right of every url as follows -
URL + ;jsessionid=0BBCDA876A12
For example -
www.gettechnotes.com;jsessionid=0BBCDA876A12
Note - Container will first try to use cookie for session tracking and fall back to URL Rewriting if client browser does not accept cookies.

For URL Rewriting HttpServletResponse provides the following two methods -

1- encodeURL() - This method attach sessionID (jsessionid) at the end of the specified URL. If encoding is not required (i.e. client accepts cookies), It returns the URL unchanged.
It has the following syntax -
public String encodeURL(String URL)
It returns the specified URL by attaching seesionID to it.                 
For example -
 out.print("<a href=\"" + response.encodeURL("Gallery") + "\">Gallery</a>");
 out.print("<a href=\"" + response.encodeURL("Logout") + "\">Logout</a>");            

2- encodeRedirectURL() - This method works with sendRedirect() method. We may require to use session while redirecting the request to some other url. For such cases we can use encodeRedirectURL() method to encode url.
This method also does the same work i.e. attach sessionID (jsessionid) at the end of the specified URL. If encoding is not required (i.e. client accepts cookies), It returns the URL unchanged.
It has the following syntax -
public String encodeRedirectURL(String URL)
It returns the specified URL by attaching seesionID to it.    
For example -
//Attach sessionId to URL
String url = response.encodeRedirectURL("Home");
// redirect to the URL
response.sendRedirect(url);    


Note 1 - We can perform URL Rewriting for dynamic pages (Servlet and JSP) only. We can not do URL Rewriting for HTML pages.
Note 2 - URL Rewriting is automatically handled by web container; we only need to encode URL's. And URL Rewriting only comes into picture if client browser does not accept cookies.

Example -

In this example we will use session to identify subsequent client requests whether client web browser accept cookies or not.
This is the same example as we used in HttpSession, the only difference is, and here we are taking care of session tracking even if client does not accept cookies.
index.html or index.jsp -
<!DOCTYPE html>
<html>
 <head>
   <title>URL_Rewriting_Demo</title>
 </head>
 <body>
      
  <form method="post" action="LoginCheck">
             
   <table border="1px">
     <tr>
       <td>User Name </td>
       <td><input type="text" name="t1" placeholder="Enter name"></td>
     </tr>
     <tr>
      <td>Password </td>
      <td><input type="password" name="t2" placeholder="Enter password"></td>
     </tr>
    <tr>
      <td><input type="submit" value="Login"></td>
      <td><input type="reset" value="Reset"></td>
    </tr>
    </table>
  
    </form>
    </body>
</html>    
2 - Create a package named servs and within servs create following servlets -
LoginCheck Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginCheck extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try
        {
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession();
            String nm = request.getParameter("t1");
            String ps = request.getParameter("t2");
           if(nm.equals("admin") && ps.equals("123"))
            {
                session.setAttribute("Name", nm);
                String url = response.encodeRedirectURL("Home");
                response.sendRedirect(url);
            }
            else
            {
                String url = response.encodeRedirectURL("index.html");
                response.sendRedirect(url);
            }
            
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}
        

Home Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Home extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try
        {
            HttpSession session = request.getSession();
            if(session.getAttribute("Name") == null)
            {
             String url = response.encodeRedirectURL("index.html");
                response.sendRedirect(url);
            }
            PrintWriter out = response.getWriter();
            out.println("<h1 style='padding:10px'>Welcome to Home</h1>");
            out.println("<hr>");
            out.print("<a href=\""+ response.encodeURL("Gallery") +"\">Gallery</a>");
            out.print("<a href=\""+ response.encodeURL("Logout") +"\">Logout</a>");

        } 
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }   
}    

Gallery Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Gallery extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        try
        {
            HttpSession session = request.getSession();
            if(session.getAttribute("Name") == null)
            {
                String url = response.encodeRedirectURL("index.html");
                response.sendRedirect(url);
            }
            PrintWriter out = response.getWriter();
            out.println("<h1>Welcome to gallery</h1>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Logout Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Logout extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       try
       {
           HttpSession session = request.getSession();
           session.invalidate();  // destroy all sessions and go back to Login form.
           String url  =response.encodeRedirectURL("index.html");
           response.sendRedirect(url);
       }
       catch(Exception ex)
       {
           System.out.println(ex);
       }
    }
}    

3- web.xml Add the following code to web.xml -
<web-app>
    <servlet>
        <servlet-name>LoginCheck</servlet-name>
        <servlet-class>servs.LoginCheck</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Home</servlet-name>
        <servlet-class>servs.Home</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Gallery</servlet-name>
        <servlet-class>servs.Gallery</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Logout</servlet-name>
        <servlet-class>servs.Logout</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginCheck</servlet-name>
        <url-pattern>/LoginCheck</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Home</servlet-name>
        <url-pattern>/Home</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Gallery</servlet-name>
        <url-pattern>/Gallery</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Logout</servlet-name>
        <url-pattern>/Logout</url-pattern>
    </servlet-mapping>
</web-app>        

4- Now run project, It will show you index.html page, enter username and password and click Login button -



If we enter correct user name and password(admin/123), it will display following output -



Now copy the url from web browser and open some other web browser and enter copied url there.


So now web container redirect us to login page if we want to enter to home page without proper login.
And most importantly we do not need to be worried about whether client browser accepts cookies or not.