java – 在Struts 2和Struts中使用cookies

我有以下(缩短)struts2动作:
public class MyAction extends BaseAction implements CookiesAware {

  public String execute() {

    if (cookiesMap.containsKey("BLAH"))
      blah=Integer.parseInt(cookiesMap.get("BLAH"));

      return "success";
  }

  // For handling cookies
  Map<String,String> cookiesMap;
  @Override
  public void setCookiesMap(Map<String,String> cookiesMap) {
    this.cookiesMap = cookiesMap;
  }
}

当我做’cookieMap.containsKey’时,我得到一个空指针异常 – 在我看来,setCookiesMap没有被调用.我已经实现了CookiesAware接口,所以我会认为它应该被调用 – 我错过了这里的东西?

谢谢

解决方法

看起来struts只支持读取cookie,你必须去servlet响应来实际设置一个cookie.

最后,我已经选择完全绕过struts2 cookie支持,直接转到servlet请求/响应对象进行阅读和写入:

public class MyAction extends ActionSupport implements ServletResponseAware,ServletRequestAware {

  public int division;

  public String execute() {

    // Load from cookie
    for(Cookie c : servletRequest.getCookies()) {
      if (c.getName().equals("cookieDivision"))
        division=Integer.parseInt(c.getValue());
    }

    // Save to cookie
    Cookie div = new Cookie("cookieDivision",String.format("%d",division));
    div.setMaxAge(60*60*24*365); // Make the cookie last a year
    servletResponse.addCookie(div);

    return "success";
  }

  // For access to the raw servlet request / response,eg for cookies
  protected HttpServletResponse servletResponse;
  @Override
  public void setServletResponse(HttpServletResponse servletResponse) {
    this.servletResponse = servletResponse;
  }

  protected HttpServletRequest servletRequest;
  @Override
  public void setServletRequest(HttpServletRequest servletRequest) {
    this.servletRequest = servletRequest;
  }
}

并且在struts.xml或web.xml中没有这个方法的配置,这是一个好处.所以我对这个解决方案感到满意,即使它在不好的光线下画了struts2.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...