开发者

unable to add a cookie included in JSP via jsp:include

开发者 https://www.devze.com 2023-04-06 20:27 出处:网络
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.

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 frag开发者_开发技巧ment 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.


The <jsp:include> uses under the covers RequestDispatcher#include() and its docs say:

...

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.

...

(emphasis mine)

Cookies are to be set in the response header. So it stops here. Consider the compile time variant <%@include%>, it get literally inlined in the main JSP's source.


Source code:

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

Target code:

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

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

res.addCookie(cookie);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号