简体   繁体   English

无法使用JSP设置Cookie

[英]Can't set a cookie with JSP

Can't set a cookie through JSP. 无法通过JSP设置Cookie。 But JavaScript works good. 但是JavaScript很好用。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
...//imports and taglibs
<%@ page import="javax.servlet.http.Cookie" %>
<%
    Cookie cookie = new Cookie("testJSP", "testJSP");
    cookie.setMaxAge(365*24*60*60);
    response.addCookie(cookie);
%>
<div ...
   <span><%=request.getCookies()[0].getName() + " " + request.getCookies()[1].getName()%></span>

I will get a JSESSIOID and a name "test" of my cookie that I set through JS, but if I try to add 我将获得一个JSESSIOID和一个通过JS设置的cookie的名称“ test”,但是如果我尝试添加

request.getCookies()[2].getName()

I'll get an "HTTP Status 500 - An exception occurred processing JSP page /WEB-INF/jsp/issueGrid.jsp at line 18" Also in Firebug I don't see cookie that I set from JSP. 我将收到“ HTTP状态500-在第18行处理JSP页面/WEB-INF/jsp/issueGrid.jsp时发生异常”。在Firebug中,我也看不到我从JSP设置的cookie。 Can you help me? 你能帮助我吗? Where is my problem? 我的问题在哪里? Thx! 谢谢!

When doing response.addCookie(cookie); 当做response.addCookie(cookie); you are actually adding the cookie to the current HTTP response. 您实际上是将cookie添加到当前的HTTP响应中。

To check the cookies defined, try to avoid literal indexes and prefer looping over the list of cookies (or better use jstl c:foreach : 要检查已定义的cookie,请尝试避免使用文字索引,而应优先遍历cookie列表(或最好使用jstl c:foreach

<% for (int i = 0; i < (request.getCookies() != null ? request.getCookies().length : 0); i++) { %>
    <li>
        <%= request.getCookies()[i].getName() + "=" + request.getCookies()[i].getValue()%>
    </li>
<% } %>

BTW if you try to access the cookie (your index 2) you add to the response on the same payload you won't get it, hence a NullPointerException, hence a HTTP 500 顺便说一句,如果您尝试访问cookie(您的索引2),则将您添加到响应的Cookie上,但不会获得相同的有效负载,因此会出现NullPointerException,因此会出现HTTP 500

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM