Currently, I am using
request.getRequestDispatcher("thePage.html").forward(request, response);
in my servlet to the user the new page. But the URL of the servlet stays in browser address bar. I want the URL of the target page to be shown in browser address bar, instead of the initial servlet URL. How do I accomplish this?
forward() method This method forwards a request from a servlet to another servlet on the same server. It allows one servlet to do the initial processing of a request, obtains the RequestDispatcher object, and forwards the request to another servlet to generate the response.
The sendRedirect() method is executed on the client-side. The request is transferred to another resource to a different server.
Redirecting the Request To do this, we use the sendRedirect method belonging to the HttpServletResponse interface: response. sendRedirect("https://www.google.com"); This is useful when we want to send the user to a different domain or server outside of our web application.
This is also called server side redirect. A RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request.
You can do response.sendRedirect("thePage.html")
, but then that page needs to be directly accessible from the Internet. In particular, it can be accessed directly without going to the servlet first. It will also incur an additional roundtrip (whereas a forward just returns the result within the same request-response cycle).
Depending on what you are trying to do, you should probably also look at Servlet Filters and the possibility to associate any name (including "thePage.html" and path prefixes) to a Servlet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With