关于cookie的问题

本文探讨了在Struts框架中实现用户登录状态保存及注销过程中遇到的Cookie管理难题。具体表现为点击一次退出按钮无法完全清除Cookie,需点击两次才能生效。文章提供了详细的代码示例,并尝试通过设置Cookie路径来解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天在struts中弄了一下cookie,有一个比较郁闷的问题.流程是这样的.
用户登陆后.如果选择了记住密码就添加一个cookie;如果点击退出则清除cookie.同时返回到主面.主页面同时又执行了一个action.在这个action中又获取了一次cookie判断有没有值.

现在的问题是:我需要点击两次退出,才能清除cookie.

也不知道是不是路径的问题,于是在添加cookie的时候设置了一个setPath.但是在获取cookie的时候,得到path却是null.

贴一些代码

登陆:
HttpServletResponse response = (HttpServletResponse) ActionContext
.getContext().get(StrutsStatics.HTTP_RESPONSE);
if (ifSavePwd != null) {
userId = users.get(0).getUserId();
cookie = new Cookie(cookieName, Integer.toString(userId));
cookie.setMaxAge(100000000);
cookie.setPath("/weare/");
response.addCookie(cookie);

}


退出:
for (int i = 0; i < cookies.length; i++) {
if ((cookieName).equals(cookies[i].getName())) {
try {
// userId = Integer.parseInt(cookies[i].getValue());
cookie = cookies[i];//new Cookie(cookieName, null);
cookie.setMaxAge(0);
cookie.setPath("/weare/");
response.addCookie(cookie);
// session.remove("userName");
} catch (Exception e) {
e.printStackTrace();
}
}
}


点击退出后返回的页面中要执行的action:

HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(StrutsStatics.HTTP_REQUEST);
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return ERROR;
}
session = ActionContext.getContext().getSession();
for (int i = 0; i < cookies.length; i++) {
if ((cookieName).equals(cookies[i].getName())) {
try {
userId = Integer.parseInt(cookies[i].getValue());
users = this.userService.listUser(userId, "");
if (users != null && !users.isEmpty()) {

User user = users.get(0);
session.put("userName", user.getUserName());
session.put("userId", user.getUserId());
session.put("userState", user.getUserState());
}
return SUCCESS;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值