Enjoying Java & Servlet Tutorials?
Subscribe to Ram N Java for hands-on, practical Java guides and clear web development tutorials!
🔔 Subscribe to Ram N JavaWhat is Send Redirect in Java Servlets?
In Java web applications, sendRedirect is a mechanism provided by the HttpServletResponse interface that redirects a client browser to a different resource. Unlike request forwarding, which occurs entirely on the server side, a redirection involves communication between the client (browser) and the server.
When you call response.sendRedirect("url"), the servlet container sends an HTTP response back to the browser with an HTTP status code 302 (Found) along with a Location header containing the destination URL. Upon reading this response, the browser automatically sends a brand new GET request to the specified URL.
How Control Transfers Within the Same Web Container
In this demonstration, control is transferred between two servlets hosted inside the same Tomcat web container:
- LoginServlet (mapped to /login): Handles incoming user credentials submitted via a POST request from
index.html. - WelcomeServlet (mapped to /welcome): Welcomes authenticated users and displays output directly to the browser.
When valid credentials are provided, LoginServlet invokes:
response.sendRedirect("welcome");
The browser receives status code 302, detects the target location http://localhost:8080/sendredirectdemo/welcome, and initiates a clean GET request to display the welcome screen.
Key Takeaways
- Two Requests & Two Responses: Redirection requires two distinct round-trips between the client and server.
- URL Updates in the Browser: The browser address bar updates to show the target resource URL.
- HTTP Status Code 302: Indicates a temporary redirect to the browser.
- Different Scope: Request attributes set in the initial servlet are not carried over to the redirected servlet because a new request is created.
Recommended Related Tutorials
Continue mastering Java Servlets with these related video guides from Ram N Java:
Click here to watch in Youtube : https://www.youtube.com/watch?v=oWD-x1dIDSc
Click the below Image to Enlarge
No comments:
Post a Comment