2011-07-28 27 views
3

有没有简单的方法将会话对象存储在cookies中,而不是存储在Struts2中?使用Struts2将会话对象保存在Cookies中

感谢

+1

不是真的。 cookie数据是有限制的,因此您无法在cookie中存储太多内容。如果你正在讨论存储简单的数据,比如字符串,数字,布尔值或者其他简单类型,那么cookies就可以工作,但是如果你想将一个复杂的对象序列化为一个cookie,你可能会遇到问题。此外,您需要小心保护自己免受客户在您不期待的状态下传输对象的影响。 –

回答

2

你可以尝试设置你需要的cookie值,那么你可以用一个拦截器或操作读它,这取决于你所需要的。这里是我如何在Struts2中设置Cookie。

的setCookie方法方法中,作为参数传递响应,cookie的名称,cookie值和周期

响应:

HttpServletResponse response = (HttpServletResponse) 
ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE); 

和周期,是这样的: 60 * 60 * 24 * 365(一年)

public static void setCookie(HttpServletResponse response, String name, String value, int period) { 

    try { 

     Cookie div = new Cookie(name, value); 
     div.setMaxAge(60 * 60 * 24 * 365); // Make the cookie last a year 
     response.addCookie(div); 

    } catch (Exception e) { 
     Logger.getLogger(StrutsUtils.class.getName()).log(Level.INFO, "message", e); 
    } 
} 

的的getCookie方法中,作为参数传递请求对象和cookie的名称

请求:

HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST); 


public static String getCookie(HttpServletRequest request, String name) { 

    String value = null; 

    try { 

     for (Cookie c : request.getCookies()) { 
      if (c.getName().equals(name)) { 
       value = c.getValue(); 
      } 
     } 

    } catch (Exception e) { 
     Logger.getLogger(StrutsUtils.class.getName()).log(Level.INFO, "message", e); 
    } 

    return value; 
}