[英]Get cookie value in jsp
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页面上,当我尝试访问此注释时,它返回了null,
<%
Cookie my = null;
my.getComment();%>
How do I get the comment value set in java to my jsp page?? 如何获取Java中设置到我的jsp页面的注释值?
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 b
if you want to use it in JSP code. 然后可以在HTMLs中按${xyz}
使用is,如果要在JSP代码中使用b
则可以使用b
。
You are setting my
to null
and accessing the comment. 您将my
设置为null
并访问评论。 This will throw NullPointerException
.Change your code to 这将引发NullPointerException
将代码更改为
<%
Cookie[] my = request.getCookies();
for(int i=0;i<my.length;i++){
String comment = my[i].getComment();
out.println(comment);
}
%>
Note : Please avoid using Scriptlets . 注意:请避免使用Scriptlets 。 they are NOT recommended 不推荐他们
Cookie : cookie['cookie_name']
Cookie : cookie['cookie_name']
Cookie Value : cookie['cookie_name'].value
Cookie值 : cookie['cookie_name'].value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.