JSP转发和重定向的区别
请解释一下 jsp:forward
和 redirect
之间的区别。
每种情况都发生了什么?
Please explain the difference between jsp:forward
and redirect
.
What is happening in each case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
redirect 将响应状态设置为 302 [1],并在
Location
标头中设置新 url,并将响应发送到浏览器。然后浏览器根据 http 规范,再次向新 url 发起请求forward 发出另一个请求,这完全发生在服务器上。 servlet 容器只是将相同的请求转发到目标 url,而浏览器不知道这一点。因此,在处理新 url 时,您可以使用相同的请求属性和相同的请求参数。并且浏览器不会知道 url 已更改(因为它完全发生在服务器上)
redirect sets the response status to 302 [1], and the new url in a
Location
header, and sends the response to the browser. Then the browser, according to the http specification, makes another request to the new urlforward happens entirely on the server. The servlet container just forwards the same request to the target url, without the browser knowing about that. Hence you can use the same request attributes and the same request parameters when handling the new url. And the browser won't know the url has changed (because it has happened entirely on the server)
我听过关于重定向和转发的有趣解释。想象一下,您需要朋友提供一些服务。提供什么服务并不重要。假设你的朋友无法帮助你,但知道谁可以。
如果他告诉你:“我无法处理这个问题,但我知道谁可以。这是他的电话号码。给他打电话。”他会重定向你的请求。
如果他告诉你:“没问题”,并亲自打电话给那个人,而不通知你让另一个人来处理你的愿望,他就会转发你的请求。然后,你的朋友就会得到你的愿望整理结果并转发给你。
I've heard interesting explanations of redirect and forward. Imagine that you need some service from your friend. It doesn't matter what service. Suppose that your friend can't help you but knows who can.
He would REDIRECT your request if he would tell you: "I can't handle this, but I know who can. Here his phone number. Call him."
He would FORWARD your request if he would tell you: "No problem" and calls that man by himself without notifying you about involving another person in handling your desire. Then, your friend will get the result of sorting out your wish and transmit it to you.
与转发相比,重定向也较慢,因为它必须经过浏览器并等待浏览器发出新请求,因此也会导致重定向后请求范围对象不可用。
Redirect is also slower compared to forward because it has to go through the browser and wait for the browser to make a new request, and also therefore causing request scope objects to be unavailable after redirect.
重定向:
转发:
是将所请求的资源简单地展示给用户的过程。它完全发生在服务器端。
Redirect :
Forward:
It is the process of simply displaying the requested resource to the user. It happens entirely on the server side.
这篇文章给出了关于使用一个很好的转发与重定向的非常好的解释现实世界的例子。
This post gives a really good explanation about forward vs redirect using a nice real world example.
当您转发请求时,
请求和响应对象都会被传输。
-url 保持不变。
当您将请求重定向到另一个 JSP/servlet 时,
请求和响应对象不会传输到新对象。
-Url 更改为新页面的目录。
When you forward a request,
-request and response objectsare transferred.
-url stays the same.
When you redirect the request to another JSP/servlets,
-request and response objects are not transferred to new object.
-Url changes to the directory of new page.