在Struts 2和Struts中使用cookie


问题内容

我有以下(缩短的)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;
  }
}

当我执行’cookiesMap.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,我也对它感到满意。