Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've got the following (shortened) struts2 action:

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;
  }
}

I get a null pointer exception when i do 'cookiesMap.containsKey' - it seems to me that setCookiesMap isn't being called. I've implemented the CookiesAware interface so i would have thought that it should be getting called - have i missed something here?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

It appears that struts only supports reading cookies, you have to go to the servlet response to actually set a cookie.

In the end, i've opted to bypass the struts2 cookie support entirely and go directly to the servlet request/response objects for both reading and writing:

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;
  }
}

And there's no configuration required for this method in either struts.xml or web.xml, which is a bonus. So i'm happy with this solution, even if it does paint struts2 in a poor light.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...