Java 在jsp中获取cookie值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22808565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get cookie value in jsp
提问by Code
on my Java servlet I've initialized a cookie as below,
在我的 Java servlet 上,我初始化了一个 cookie,如下所示,
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie thecookie = new Cookie("thecookie", loc);
thecookie.setMaxAge(60*60*24);
response.addCookie(thecookie);
and in cookie comments I've added some data as below,
在 cookie 评论中,我添加了一些数据,如下所示,
thecookie.setComment(fileTxt);
Now on my jsp page when I try to access this comment it returned a null,
现在在我的 jsp 页面上,当我尝试访问此评论时,它返回了一个空值,
<%
Cookie my = null;
my.getComment();%>
How do I get the comment value set in java to my jsp page??
如何将java中设置的注释值获取到我的jsp页面??
采纳答案by Code
In your JSP use,
在您的 JSP 使用中,
<%
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null)
{
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
String b = cookie.getComment();
request.setAttribute("xyz", b);
}
}
%>
and then you can use is by ${xyz}in htmls and use bif you want to use it in JSP code.
然后你可以${xyz}在 htmls 中使用 is by ,b如果你想在 JSP 代码中使用它,请使用它。
回答by Keerthivasan
You are setting myto nulland accessing the comment. This will throw NullPointerException.Change your code to
要设置my到null和访问注释。这将抛出NullPointerException.Change 你的代码
<%
Cookie[] my = request.getCookies();
for(int i=0;i<my.length;i++){
String comment = my[i].getComment();
out.println(comment);
}
%>
Note : Please avoidusing Scriptlets. they are NOTrecommended
注意:请避免使用Scriptlets。他们不推荐
回答by Kotes
Cookie: cookie['cookie_name']
饼干:cookie['cookie_name']
Cookie Value: cookie['cookie_name'].value
饼干价值:cookie['cookie_name'].value

