URL Rewriting using Java Servlet

Last Updated : 12 May, 2026

URL rewriting is a session tracking technique in Java Servlet where data such as a username or session ID is appended to the URL. Since HTTP is a stateless protocol, URL rewriting helps the server identify the same client across multiple requests, especially when cookies are disabled.

  • Session information is passed through URL query parameters.
  • It helps maintain client state between multiple requests.
  • Commonly used when browser cookies are disabled.

Why Do We Need URL Rewriting?

In web applications, the server often needs to identify the same user during multiple requests. For example, after login, the server should remember the user's information until logout. Since HTTP is stateless, URL rewriting is used to pass user-related information from one servlet to another through the URL.

Syntax:

out.print("<a href='SecondServlet?uname=" + n + "'>visit</a>");

In the above statement:

  • SecondServlet is the target servlet.
  • uname is the query parameter.
  • n contains the username value.

The generated URL looks like:

http://localhost:8080/ProjectName/SecondServlet?uname=Ravi

Using Annotation in Servlet

In Java Servlet, annotations are used to configure servlets without creating a web.xml file. The @WebServlet annotation maps a URL pattern directly to the servlet class, making configuration simpler and easier to manage.

  • @WebServlet is an annotation provided by the Servlet API.
  • It is written just above the servlet class declaration.
  • The value inside ("/ServletName") defines the URL pattern used to access the servlet.
  • When the client sends a request to this URL, the corresponding servlet gets executed.

Syntax:

@WebServlet("/ServletName")

Note :Generally we write web.xml file for request dispatcher but in this example we use annotation so their is no need of creating web.xml file.

Example of Session tracking using URL rewriting using annotation

Step 1: Create the HTML Form

First, create an HTML page that accepts the username from the user and sends the request to FirstServlet.

html
<!-- Save this file as Index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="submit"/>  
</form>  
</body>
</html>

The browser displays a simple HTML form containing a text field to enter the username and a submit button to send the request to the servlet.

Step 2: Create the First Servlet

Now create a servlet that receives the username and appends it to the URL using URL rewriting.

Java
package GeeksforGeeks;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/FirstServlet") // annotation

// this annotation is used for replacing xml file
public class FirstServlet extends HttpServlet {

    // class name is FirstServlet which extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    {
        try {
            response.setContentType("text/html");
           /* The response's character encoding is only set 
from the given content type if this method 
is called before getWriter is called. 
This method may be called repeatedly to 
change content type and character encoding.*/
            PrintWriter out = response.getWriter();


            /*T he Java PrintWriter class ( java.io.PrintWriter ) enables you to 
          write formatted data to an underlying Writer . 
         For instance, writing int, long and other primitive data
          formatted as text, rather than as their byte values*/
            String n = request.getParameter("userName");
           
//request.getParameter takes the value from index.html file
  // where name is username
            out.print("Welcome " + n);

// out.println is used to print on the client web browser

 //url rewriting is used for creating session 
//       it will redirect  you to SecondServlet page
            out.print("<a href='SecondServlet?uname=" + n + "'>visit</a>");

            out.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

After submitting the form, the browser displays a welcome message along with a hyperlink, and the URL changes to include the username as a query parameter.

Step 3: Create the Second Servlet

Next, create another servlet that reads the value passed through the URL.

Java
package GeeksforGeeks;

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

@WebServlet("/SecondServlet") // annotation
public class SecondServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    {
        try {

            response.setContentType("text/html");
            /*
             * The response's character encoding is only set from the given
             * content type if this method is called before getWriter is called.
             * This method may be called repeatedly to change content type and
             * character encoding.
             */
            PrintWriter out = response.getWriter();
            /*
             * The Java PrintWriter class ( java.io.PrintWriter ) enables you to
             * write formatted data to an underlying Writer . For instance,
             * writing int, long and other primitive data formatted as text,
             * rather than as their byte values
             */
            // getting value from the query string
            String n = request.getParameter("uname");
            out.print("Hello " + n);
            /* out.println is used to print on the client web browser */
            out.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output:

Program flow

Explanation: When you deploy your project in eclipse the first page which is loaded in the HTML form whose form action is first servlet so the control will go to servlet1. In this case, we name servlet1 as FirstServlet where the username is printed. In FirstServlet we provide url where we transfer the control to servlet2 using url rewriting. In our case we name servlet2 as SecondServlet.

Comment