[英]Why does servlet name stay in url after RequestDispatcher.forward?
I am making a JSP/Servlet web app which starts with log in page. 我正在制作一个以登录页面开头的JSP / Servlet Web应用程序。 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: 用户输入登录信息后,称为LoginServlet
的servlet处理数据,如果登录成功,则servlet将用户重定向到MainPage.jsp
如下所示:
RequestDispatcher rd = request.getRequestDispatcher("MainPage.jsp");
rd.forward(request,response);
It works. 有用。 It takes me to MainPage.jsp, only the URL is NOT : 它带我到MainPage.jsp,只有URL 不是 :
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
. 注意:我不知道这是否重要,但是在form
元素的action
属性中(在登录页面中)我放置了LoginServlet
。 Like this: 像这样:
<form action="LoginServlet" method="POST">
Thanks in advance! 提前致谢!
forward
is an action that happens within a single request-response cycle. forward
是在单个请求-响应周期内发生的操作。 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. 您的浏览器将单个请求发送到/someUrl
,服务器将处理该请求,并返回响应。
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. 您可能必须使客户端(浏览器)将另一个请求发送到另一个URL,这可能是由于重定向所致。
forward()
method won't change the url. forward()
方法不会更改网址。 sendRedirect()
in HttpServletResponse
do change the url as well. HttpServletResponse
sendRedirect()
也会更改网址。
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. 这意味着所有以前的数据都将消失,您将收到一个全新的请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.