0

From a servlet "servlet.html", I can call another servlet "servlet2.html" like this:

dispatcher = getServletContext().getRequestDispatcher("/servlet2.html");

However, in the brouzer, the URL is from the first servlet:

http://localhost:8080/project/servlet.html

I would like it to be the URL of the current servlet.

http://localhost:8080/project/servlet2.html

Is that possible?

morbidCode
  • 2,325
  • 5
  • 21
  • 47

1 Answers1

0

What you want is to perform redirect: response.sendRedirect("/servlet2.html").

TL;DR;

Dispatcher will just pass request to another servlet, so client does not see any change.

When you are performing redirect then server is sending response with HTTP code 302 and parameter Location with full URL to servlet2.html. When a web browser will recieve this kind of response it will perform another request to URL given in Location parameter.

Here you can find more explanations.

Community
  • 1
  • 1
Arek
  • 2,896
  • 3
  • 21
  • 32
  • when I wrote response.sendRedirect("/servlet2.html"), it gives an error saying localhost:8080/servlet2.html cannot be found, which is true because that URL is wrong, but when I remove the "/" like so response.sendRedirect("servlet2.html") it now works. Can you explain why it worked without the "/"? – morbidCode Jun 14 '15 at 14:03
  • Sorry, my mistake. "/" refers to root of the aplication. Without it you refer to a relative path in relation to path of the original request. – Arek Jun 15 '15 at 04:59