论坛首页 Java企业应用论坛

关于cookie的问题

浏览 6819 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (2)
作者 正文
   发表时间:2008-11-13  
这几天在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();
				}
			}
		}



   发表时间:2008-11-13  
path是给BROWSER用的吧? 我。。。。。不确定, 没有详细研究过。
0 请登录后投票
   发表时间:2008-11-13  
或许知道问题的所在了,当我退出时设置cookie失效.并没有立即失效.

也就是第一次点击退出后.我在等了一会儿.在点击首页的时候.就失效了..怎样才能立即生效呢?
0 请登录后投票
   发表时间:2008-11-13  
点击退出的时候把COOKIE删掉不行吗?
0 请登录后投票
   发表时间:2008-11-13   最后修改:2008-11-13
清除可能需要一些时间.没有立即生效.也就是我点击退出后.跳转的页面会走另外一个action.而这个action会对 cookie做判断.在点击退出到执行跳转页面中action之间. cookie还存在.
0 请登录后投票
   发表时间:2008-12-22   最后修改:2008-12-22
将退出的forward启用重定向即可即时生效
例:<forward name="logout" path="logout.jsp" redirect="true" />
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics