Java – using cookies in struts 2 and struts
•
Java
I have the following (shortened) struts 2 actions:
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; } }
When I do 'cookiemap When 'containskey', I get a null pointer exception - in my opinion, setcookiesmap is not called I've implemented the cookiesaware interface, so I think it should be called - what did I miss here?
thank you
Solution
It seems that struts only supports reading cookies. You have to go to the servlet response to actually set a cookie
Finally, I have chosen to bypass Struts2 cookie support completely and go directly to the servlet request / response object for 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 in struts XML or web There is no configuration of this method in XML, which is a benefit So I'm satisfied with this solution, even if it draws struts 2. 0 in bad light
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码