5

Cookies are not getting added to the browser when the code adding the cookie is part of a fragment of JSP (includes.jsp) included in the primary page (main.jsp) via JSP:INCLUDE.

The code works fine when it is part of the primary page (main.jsp). However, I need to add the cookie via the fragment since that fragment is used in dozens of pages where I want the cookie to get added.

Note: The jsp:include is part of the header section of main.jsp (the fragment also adds a number of javascript and css references)

Here is the snippet:

Cookie cookie = new Cookie ("test","test cookie");
cookie.setMaxAge(365 * 24 * 60 * 60);
cookie.setPath("/");
response.addCookie(cookie2);

The above works fine when it is part of the main.jsp but doesn't work when it is part of the fragment added to main.jsp via . it is almost as if the response object is being reset after the fragment is rendered.

4

2 回答 2

6

封面下的<jsp:include>用途RequestDispatcher#include()及其文档说:

...

ServletResponse对象的路径元素和参数与调用者的保持不变。包含的 servlet 不能更改响应状态码或设置标头;任何进行更改的尝试都会被忽略

...

(强调我的)

Cookie 将在响应标头中设置。所以就到此为止了。考虑编译时变体<%@include%>,它在主 JSP 的源代码中被直接内联。

于 2011-09-23T18:02:32.963 回答
0

源代码:

request.setAttribute(“res”, response);
<jsp:include page=“url” />

目标代码:

HttpServletResponse res = (HttpServletResponse)request.getAttribute(“res”);

//cookie create
Cookie cookie = new Cookie(“test”, “test”);

res.addCookie(cookie);
于 2018-03-27T00:29:11.867 回答