🧠 What is URL Rewriting?
✅ URL Rewriting is a technique where you append extra information (like a session ID or user data) into the URL itself,
so that the server can track the user even if the client doesn’t support cookies.
📖 In simple words:
“If the browser can’t or won’t store cookies,
then pass the session ID inside the URL itself.” 🎯
🎯 How URL Rewriting Looks
✅ Example of a URL with rewriting:
https://example.com/shop;JSESSIONID=ABC123XYZ456
;JSESSIONID=ABC123XYZ456
is the rewritten part.
It carries the session ID back and forth between client and server.
🚀 Why Use URL Rewriting?
Reason | Explanation |
---|---|
Cookies disabled | Some browsers block cookies, but we still need session tracking. |
Fallback mechanism | Servlet containers automatically fall back to URL rewriting if cookies don’t work. |
Control | You explicitly control how session data is passed in links/forms. |
⚙️ How to Implement URL Rewriting in Servlets
✅ Java servlets provide built-in support:
When building a link:
String rewrittenUrl = response.encodeURL("profile.jsp");
encodeURL()
will automatically:- If cookies work ➔ return normal URL.
- If cookies don’t work ➔ append session ID into the URL.
✅ Usage in servlet response:
PrintWriter out = response.getWriter();
out.println("<a href='" + response.encodeURL("profile.jsp") + "'>Profile</a>");
✅ Similarly, when redirecting:
response.sendRedirect(response.encodeRedirectURL("welcome.jsp"));
🔥 Very Important:
- You must use
encodeURL()
andencodeRedirectURL()
if you want session tracking to work even when cookies are disabled. - If you just hard-code URLs without encoding, you risk breaking sessions for cookie-disabled users.
⚡ Example Without and With URL Rewriting
Case | URL |
---|---|
Without URL rewriting (normal) | /profile.jsp |
With URL rewriting (cookies disabled) | /profile.jsp;JSESSIONID=ABC123XYZ456 |
🛠️ When exactly does the server use URL rewriting?
- Servlet container (e.g., Tomcat) checks:
- Are cookies enabled?
- Did the browser return the
JSESSIONID
cookie?
- If no cookie, and you used
encodeURL()
, then the server adds;JSESSIONID=...
to URLs automatically.
⚡ Quick Practical Tip:
Situation | Best Practice |
---|---|
You create a URL manually | Always call encodeURL() |
You send a redirect | Always call encodeRedirectURL() |
🧠 Quick Memory Trick:
“URL Rewriting is Plan B: If the browser won’t carry cookies,
carry the session ID inside the URL!” 🎯
🔥 Quick Summary Table:
| | Cookies | URL Rewriting | |:—|:—| | Client needs to store something? | ✅ Yes | ❌ No | | Session ID visible? | ❌ No | ✅ Yes (in URL) | | Secure? | Less secure (session ID exposed in URL) | | Automatic in servlets? | ✅ With encodeURL()
|