我在 jsp 中遇到重定向问题,页面仍然存在并且不会抛出任何错误。
当我直接在 login.jsp 中编写脚本时,我可以进行重定向,例如
<%
String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);
%>
<t:login title="Client Login">
..........
</t:login>
但是,当我将文件分成三个并包含它时,我无法重定向。下面是我的实现。
登录.jsp
<%@include file="/include/checkhandler.jsp"%>
checkhandler.jsp - 这是一个脚本,它将检查处理程序文件夹中的文件并在存在时将其包含在内。
......
request.getRequestDispatcher(handler).include(request, response);
......
login_handler.jsp 这是调度程序将包含的文件
String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);
out.println("hello world");
执行此脚本后,显示了 hello world,但它仍然停留在同一页面,没有任何错误。
最佳答案
您需要使用RequestDispatcher#forward()反而。将 checkhandler.jsp 更改为
request.getRequestDispatcher(handler).forward(request, response);
禁止服务器端包含更改响应状态代码,这是使用 sendRedirect()
时发生的情况。任何此类尝试都会被容器忽略。
来自RequestDispatcher#include()文档:
The
ServletResponse
object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
此限制是设计使然。该规范将包含的 Web 组件视为 guest ,即它无法引导流程,任何此类尝试都将被正确忽略,而不是抛出异常> 可能允许包含您可能拥有的任何 servlet。
只有托管 Web 组件(执行包含操作的组件)才能完全控制流程以及发送到客户端的响应 header 。
关于java - 当 RequestDispatcher 包含脚本时无法重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28037037/