Servlet响应上设置的Cookie在转发的JSP请求中不可用

问题描述

我有一个简单的页面,用户可以单击一个按钮,然后将其转发到新页面。但是,如果不单击前一页上的按钮就无法访问新页面。单击该按钮时,它将发送一个cookie,以检查是否单击了该按钮。如果我使用request.sendRedirect(),则效果很好。但是,当使用request.forward()时,不会。我必须多次单击按钮,然后才能发送到新页面。下面是代码

//sends cookie when button is clicked
private void connect(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {

    Cookie cookie = new Cookie("connect","connected");
    cookie.setMaxAge(1);
    
    response.addCookie(cookie);
    
    RequestDispatcher dispatcher = request.getRequestDispatcher("connectAudio.jsp");
    dispatcher.forward(request,response);
}

浏览器检查cookie是否存在,如果不存在,则表明未按下该按钮,并使用按钮将其发送回页面

<c:if test="${empty cookie['connect']}">
<c:redirect url="index.jsp">
</c:redirect>
</c:if>

解决方法

对于redirect,浏览器发送两个连续的请求,而第二个请求具有必需的cookie,因为它是由对第一个请求的响应设置的。

对于RequestDispatcher.forward(...),浏览器仅发出一个请求,该请求将传递给connectAudio.jsp。尚未为此第一个请求设置必需的cookie。

有关更多信息,请参见this page及其上的图像:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...