🚀 Master Java Servlets & Web Development!
Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical guides!
👉 Click Here to Subscribe NowWhat is URL Rewriting in Java Servlets?
HTTP is an inherently stateless protocol, which means the server does not remember user data between multiple web requests.
URL Rewriting is a fundamental session tracking mechanism where extra session information (such as a session ID or custom parameter) is appended directly to the end of a hyperlink URL as a query parameter (e.g., targetURL?paramName=value).
Unlike browser cookies, URL rewriting does not require cookie support and functions seamlessly even when cookies are disabled on the client machine.
Step 1: Create the User Input Page (index.html)
Start by creating an HTML form that collects the initial data from the client and submits it to your first servlet:
Enter User Name: <input type="text" name="userName" /><br><br>
<input type="submit" value="Proceed" />
</form>
Step 2: Rewrite the URL in the First Servlet (FirstServlet.java)
In the first servlet, read the parameter from the request and dynamically construct a hyperlink containing the user data appended in the query string:
PrintWriter out = response.getWriter();
out.println("<h2>Hello, " + userName + "!</h2>");
out.println("<p>Click the link below to continue:</p>");
out.println("<a href='SecondServlet?uname=" + userName + "'>Go to Second Servlet</a>");
Step 3: Retrieve the Data in the Target Servlet (SecondServlet.java)
When the user clicks the rewritten link, the target servlet extracts the appended query parameter via request.getParameter():
PrintWriter out = response.getWriter();
out.println("<h2>Welcome to Second Servlet!</h2>");
out.println("<p>Retrieved User Name: <strong>" + userName + "</strong></p>");
Pros and Cons of URL Rewriting
- Advantage: Works reliably across all browsers without depending on client cookie permissions.
- Advantage: No server session memory footprint is required for simple parameter forwarding.
- Limitation: Visible in the browser's address bar and history; sensitive information (like passwords) must never be sent this way.
- Limitation: Only links and navigation generated with rewritten query strings will maintain the state.
📺 Related Session Tracking Tutorials
Expand your understanding of session management in Servlets with these tutorials:
Click here to watch in Youtube : https://www.youtube.com/watch?v=0Ch2Bfea5yw
Click the below Image to Enlarge
![]() |
| Servlets : URL Rewriting Demo |
![]() |
| Servlets : URL Rewriting Demo |


No comments:
Post a Comment