[英]Java servlet - Forwarding/Redirecting from subpage
I am working on a project where I have running servlets packaged in a war that listen for requests and populate a foreign div on a separate page. 我正在开发一个项目,我在战争中运行servlet,监听请求并在单独的页面上填充外部div。 An initial request is made to servlet (a) and if there is data to display, it renders that HTML. 向servlet(a)发出初始请求,如果有要显示的数据,则呈现该HTML。 If there is NO data, it passes a query string to another servlet to handle the request and then renders a page with options to choose. 如果没有数据,它会将查询字符串传递给另一个servlet以处理请求,然后呈现包含要选择的选项的页面。
I am running Tomcat 6 with Windows Server 2008. 我正在使用Windows Server 2008运行Tomcat 6。
But I run into two problems: 但我遇到两个问题:
What's the best practice to assure that I can "redirect" from an initial servlet call to another servlet using the response object from that first servlet? 确保我可以使用第一个servlet的响应对象从初始servlet调用“重定向”到另一个servlet的最佳实践是什么?
A redirect returns a HTTP 302 response with the new URL in Location
header which the client needs to deal with. 重定向返回HTTP 302响应,其中包含客户端需要处理的Location
头中的新URL。 Basically, your JS code must check the response status code if it's 302 and then extract the Location
header and then re-send a new request on it. 基本上,您的JS代码必须检查响应状态代码(如果它是302),然后提取Location
标头,然后在其上重新发送新请求。 Repeat this until the response status code is 200. 重复此操作,直到响应状态代码为200。
That it works when pasting the URL in browser's address bar is because the browser already knows how to deal with 3nn responses properly. 在浏览器的地址栏中粘贴URL时它的作用是因为浏览器已经知道如何正确处理3nn响应。 If you open up the network traffic tracker in browser's webdeveloper toolset, then you'll see that a second GET request is been fired on the new URL. 如果您在浏览器的webdeveloper工具集中打开网络流量跟踪器,那么您将看到在新URL上触发了第二个GET请求。
Another way, if the servlets run in the same container, is to just use RequestDispatcher#forward()
instead of HttpServletResponse#sendRedirect()
. 另一种方法是,如果servlet在同一个容器中运行,只需使用RequestDispatcher#forward()
而不是HttpServletResponse#sendRedirect()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.