加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在Struts 2和Struts中使用cookies

发布时间:2020-12-14 05:27:15 所属栏目:Java 来源:网络整理
导读:我有以下(缩短)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
我有以下(缩短)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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读