Chr*_*ris 10 java cookies struts2
我有以下(缩短)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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我执行'cookiesMap.containsKey'时,我得到一个空指针异常 - 在我看来,没有调用setCookiesMap.我已经实现了CookiesAware界面,所以我认为它应该被调用 - 我错过了什么吗?
谢谢
Chr*_*ris 10
看来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;
}
}
Run Code Online (Sandbox Code Playgroud)
并且struts.xml或web.xml中没有此方法所需的配置,这是一个奖励.所以我对这个解决方案感到满意,即使它确实在光线不好的情况下绘制struts2.
您还需要在struts.xml中为action定义实现Cookie Interceptor:
<action name="MyAction" class="your.fancy.app.MyAction">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="cookie">
<param name="cookiesName">BLAH</param>
</interceptor-ref>
<result>/index.jsp</result>
</action>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20435 次 |
最近记录: |