Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect Servlet to given URL

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?

like image 472
daxflame Avatar asked Mar 10 '11 06:03

daxflame


People also ask

How do I redirect one servlet to another?

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.

Why do we use sendRedirect () method?

The sendRedirect() method is executed on the client-side. The request is transferred to another resource to a different server.

How do I forward a HTTP request to another server in Java?

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.

What is difference between ServletResponse sendRedirect () and RequestDispatcher forward () method?

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.


1 Answers

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.

like image 108
Thilo Avatar answered Oct 13 '22 18:10

Thilo