当前位置: 代码迷 >> Eclipse >> cookie取值为空,该如何解决
  详细解决方案

cookie取值为空,该如何解决

热度:29   发布时间:2016-04-23 13:52:45.0
cookie取值为空
servlet里:

Cookie myName=new Cookie("username",URLEncoder.encode(name, "UTF-8"));
Cookie myPwd=new Cookie("password",pwd);
myName.setMaxAge(14*24*3600);
myPwd.setMaxAge(14*24*3600);
response.addCookie(myName);
response.addCookie(myPwd);

jsp获取cookie:

if(cookies!=null){
String s_name="";
String password="";
for(int i=0;i<cookies.length;i++){
 
Cookie cookie=cookies[i];
if(cookie.getName().equals("username")){
s_name=URLDecoder.decode(cookie.getValue(),"utf-8");
 
}else if(cookie.getName().equals("password")){
password=URLDecoder.decode(cookie.getValue(),"utf-8");
}
}
<%=s_name%>

这个s_name取不出来,是空值。请问是哪里出了问题?

------解决方案--------------------
你这个servlet执行完成后,必须要到客户端发出下一次请求才会有cookie。
如果,servlet执行完成后直接转到JSP,这个JSP是在本次不可以找到cookie.
------解决方案--------------------
if(cookie.getName().equals("username"))
改成这样
if(cookies[i].getName().equals("username"))
  相关解决方案