Struts2中的Cookie疑问

问题已经解决 写道
原因是IE只能接受Expires字段来控制过期时间,真奇怪,是不是大家看不起这样的问题竟然没人回答。
 String[] d = date.toString().split(" ");
             //IE的日期格式 Fri, 27-Aug-2010 02:38:12 GMT
             //格式化日期
             SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z",Locale.US);
             sdf.setTimeZone(TimeZone.getTimeZone("Etc/Greenwich"));
             //String expires = d[0]+", "+d[2]+"-"+d[1]+"-"+d[5]+" "+d[3]+" "+d[4];
             String expires = sdf.format(date);
             response.setHeader("Set-Cookie",AuthorizationInterceptor.COOKIE_REMEMBERME_KEY + "=\""+cookie.getValue()+"; Max-Age="+cookie.getMaxAge()+"; Path="+cookie.getPath()+";expires="+expires);
 

 

 

我最近在做Struts2的登录权限验证,使用总所周知的Cookie保存用户登陆状态。

实际过程中发现Cookie并不起效,关闭浏览器后即失效。


这是LoginAction的execute方法,Cookie是使用ServletActionContext的Response添加的

在服务器打印Cookie信息正常如下:

true
NEW cookie:37 123

 

	public String execute() throws Exception {
		// TODO Auto-generated method stub
		System.out.println(rememberMe);
		User u = new User();
		User u2 = null;
		u.setUsername(this.getUsername());
		u.setPassword(this.getPassword());
		Query q = session.createQuery("from User where username='"
				+ this.getUsername() + "'");
		if (q.list().size() == 1)
			u2 = (User) (q.list().get(0));
		session.close();
		if (u.getUsername().equals(u2.getUsername())
				&& u.getPassword().equals(u2.getPassword())) {
			ActionContext.getContext().getSession().put("id", u2.getId());
			ActionContext.getContext().getSession().put(
					AuthorityInterceptor.USER_SESSION_KEY, u2.getUsername());
			ActionContext.getContext().getSession().put("usertype",
					u2.getUsertype());
			HttpServletResponse response = (HttpServletResponse) ActionContext
					.getContext().get(StrutsStatics.HTTP_RESPONSE);
			if (Boolean.valueOf(rememberMe)) {
				Cookie cookie = new Cookie(
						AuthorityInterceptor.COOKIE_REMEMBERME_KEY, u2.getId()
								+ "==" + password);
				cookie.setMaxAge(60 * 60 * 24 * 14);
				System.out.println("NEW cookie:" + u2.getId() + " " + password);
				ServletActionContext.getResponse().addCookie(cookie);
			}
			String goingToURL = (String) ActionContext.getContext()
					.getSession().get(AuthorityInterceptor.GOING_TO_URL_KEY);
			if (StringUtils.isNotBlank(goingToURL)) {
				setGoingToURL(goingToURL);
				ActionContext.getContext().getSession().remove(
						AuthorityInterceptor.GOING_TO_URL_KEY);
			} else {
				setGoingToURL("index.action");
			}
			if (u.getUsertype() == 1)
				return "jobp";
			else if (u.getUsertype() == 0)
				return "jobh";
			else
				return "joba";
		} else {
			return LOGIN;
		}
	}

 

下面是LogoutAction的execute方法,用于清除session和Cookie。

在浏览器未关闭是调用此Action,返回是正常的,也就是可以根据Cookie的Key正确的找到Cookie并删除。

输出:

2            //这个是get到的Cookie个数,我也不明白为什么这么小,我电脑实际储存了大量Cookie
cookie removed!

 

public String execute() throws Exception {
		// TODO Auto-generated method stub
		Map session = ActionContext.getContext().getSession();
		HttpServletRequest request= (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
		if (session!=null)   {
			session.remove(AuthorityInterceptor.USER_SESSION_KEY); 
			session.remove("id"); 
			session.remove("usertype"); 
		}  
              
        Cookie[] cookies = request.getCookies();
        System.out.println(cookies.length);
        if (cookies!=null) {      
            for (Cookie cookie : cookies) {      
                if (AuthorityInterceptor.COOKIE_REMEMBERME_KEY.equals(cookie.getName())) {
                	System.out.println("cookie removed!");
                    cookie.setValue("");      
                    cookie.setMaxAge(0);      
                    response.addCookie(cookie);      
                    return "login";      
                }      
            }      
        }      
        return "login";
	}

 

下面是权限控制的Interceptor,拦截了需要登陆的Action,是能够成功拦截的,同样在浏览器关闭后就找不到Cookie了

 

private static final long serialVersionUID = 1L;
public static final String USER_SESSION_KEY="username";      
public static final String COOKIE_REMEMBERME_KEY="gavin.cookie.rememberme";      
    public static final String GOING_TO_URL_KEY="GOING_TO";

public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		ActionContext actionContext = invocation.getInvocationContext();
        HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);      
              
        Map session = actionContext.getSession();      
        if (session != null && session.get(USER_SESSION_KEY) != null){      
            return invocation.invoke();      
        }
              
        Cookie[] cookies = ServletActionContext.getRequest().getCookies();
        if (cookies!=null) { 
            for (Cookie cookie : cookies) {  
            	System.out.println(cookie.getName());
                if (COOKIE_REMEMBERME_KEY.equals(cookie.getName())) {      
                    String value = cookie.getValue(); 
                    System.out.println(value);
                    if (StringUtils.isNotBlank(value)) {      
                        String[] split = value.split("==");      
                        String userName = split[0];      
                        String password = split[1];
                        System.out.println("cookie:"+userName+" "+password);
                        try {      
                            User user = null;
                            Query q = se.createQuery("from User where id='"+userName+"'");		
                    		if(q.list().size()==1) user= (User)(q.list().get(0));
                    		if (user != null) {
                    			if(user.getPassword().equals(password)) {
                    				session.put("id" , user.getId());
                    				session.put(USER_SESSION_KEY , user.getUsername());
                    				session.put("usertype" , user.getUsertype());
                    			}
                    		}
                        } catch (Exception e) {      
                            setGoingToURL(session, invocation);      
                            return "login";      
                        }      
                    } else {      
                        setGoingToURL(session, invocation);      
                        return "login";      
                    }      
                    return invocation.invoke();      
                }      
            }      
        }      
        setGoingToURL(session, invocation);      
        return "login";
	}

 

检查一下IE的临时文件夹也没有发现相应的Cookie文件,应该是Cookie没有写入成功,Struts2的ServletResponse也不是直接的,不知道有没有影响。也不知道Localhost有没有影响……

 

新手请指教~!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值