Djole Pi
Djole Pi

Reputation: 137

Why does servlet name stay in url after RequestDispatcher.forward?

I am making a JSP/Servlet web app which starts with log in page. After user enters log in information, a servlet, called LoginServlet, processes the data and if the log in is successful the servlet redirects user to MainPage.jsp like this:

RequestDispatcher rd = request.getRequestDispatcher("MainPage.jsp");
rd.forward(request,response);

It works. It takes me to MainPage.jsp, only the URL is NOT:

http://localhost:8080/RestauRec/MainPage.jsp

it is:

http://localhost:8080/RestauRec/LoginServlet

It is not an actual problem, but still, I want to know why this is and how can I change this?

Note: I don't know if it matters or not but, in the action attribute of the form element (in the log in page) I place LoginServlet. Like this:

<form action="LoginServlet" method="POST">

Thanks in advance!

Upvotes: 2

Views: 3507

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

forward is an action that happens within a single request-response cycle. It uses the forward-to resource to complete the response.

Your browser sends a single request to /someUrl and your server handles it, returning a response.

It is not an actual problem, but still, I want to know why this is and how can I change this?

You'd have to make your client, the browser, send a different request to another URL, possibly because of a redirect.

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

forward() method won't change the url. sendRedirect() in HttpServletResponse do change the url as well.

response.sendRedirect("MainPage.jsp");  

Remember that a new request gets hit to the container when you do redirect. That means all the previous data vanishes and you'll get a brand new request.

Upvotes: 2

Related Questions