✅ First: What is sendRedirect()
doing?
When you call:
response.sendRedirect("somepage.jsp");
the server tells the browser:
“Hey browser, make a new request to somepage.jsp
!”
(using an HTTP 302 Redirect response).
BUT:
- If cookies are disabled, you still want the session (like login information) to continue working after the redirect.
- So you must include the session ID in the redirect URL.
✅ Why encodeRedirectURL()
is needed:
When you redirect, the browser leaves the current page and makes a new request.
- If cookies are enabled → fine, session continues automatically.
- If cookies are disabled → we must append
;jsessionid=XYZ
to the redirect URL manually.
But you don’t want to manually check if cookies are working every time.
→ That’s why encodeRedirectURL()
does it for you automatically!
It:
- Adds the session ID to the URL if needed.
- Returns the original URL if not needed (cookies working fine).
✅ Practical Code Example:
Imagine you have a servlet:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// User login logic ...
// After successful login, redirect to home page:
String homePage = "home.jsp";
// We encode the redirect URL to preserve session
String encodedHomePage = response.encodeRedirectURL(homePage);
// Now redirect
response.sendRedirect(encodedHomePage);
}
}
✅ What happens behind the scenes:
Cookies enabled? | What does encodeRedirectURL("home.jsp") return? | Result |
---|---|---|
Yes | "home.jsp" | No change, redirect works normally |
No | "home.jsp;jsessionid=ABCDEF1234567890" | Session ID added into URL |
✅ Key point:
If you don’t use encodeRedirectURL()
when cookies are off → the user will lose the session after redirect.
(They will look like they are logged out, or session variables will disappear.)
🔥 Easy Rule:
- If you are redirecting → always wrap the URL with
encodeRedirectURL()
. - If you are writing a link inside HTML → use
encodeURL()
.