struts2 存取cookie
摘要: 本以为配置完CookieAware,用cookieMap.add(name,value)就能自动保存cookie了,没想到cookie文件根本没变化,原来 CookieInterceptor只做了读cookie这一步,写就不管了。 CookieInterceptor:The aim of this ...
CookieInterceptor:The aim of this intercepter is to set values in the stack/action based on cookie name/value of interest.
1 public String intercept(ActionInvocation invocation) throws Exception {
2 if (LOG.isDebugEnabled())
3 LOG.debug("start interception");
4
5 // contains selected cookies
6 final Map<String, String> cookiesMap = new LinkedHashMap<String, String>();
7
8 Cookie[] cookies = ServletActionContext.getRequest().getCookies();//取出所有的cookie
9 if (cookies != null) {
10 final ValueStack stack = ActionContext.getContext().getValueStack();
11
12 for (Cookie cookie : cookies) {//轮询
13 String name = cookie.getName();
14 String value = cookie.getValue();
15
16 if (cookiesNameSet.contains("*")) {//匹配符*:任意name
17 if (LOG.isDebugEnabled())
18 LOG.debug("contains cookie name [*] in configured cookies name set, cookie with name [" + name + "] with value [" + value + "] will be injected");
19 populateCookieValueIntoStack(name, value, cookiesMap, stack);//将cookie name/value 压入栈中
20 } else if (cookiesNameSet.contains(cookie.getName())) {//else,匹配所指定的cookie name
21 populateCookieValueIntoStack(name, value, cookiesMap, stack);//将cookie name/value 压入栈中
22 }
23 }
24 }
25
26 // inject the cookiesMap, even if we don't have any cookies
27 injectIntoCookiesAwareAction(invocation.getAction(), cookiesMap);//注入action
28
29 return invocation.invoke();
30 }
所以还得自己管理。事实证明,偷懒是要不得的……
注:因为cookie value为汉字,需要先encode,否则保存时抛异常:
java.lang.IllegalArgumentException: Control character in cookie value, consider BASE64 encoding your value
1 public void addCookie(String name,String value){
2 //创建Cookie
3 Cookie cookie = new Cookie(name, URLEncoder.encode(value));
4 //设置Cookie的生命周期
5 cookie.setMaxAge(60*60*24*365);
6 ServletActionContext.getResponse().addCookie(cookie);
7 }
8
9 public void removeCookie(String name){
10 addCookie(name,"");
11 }
12
13 public String getCookie(String name){
14 String value=cookie.get(name);
15 if(value!=null)
16 return URLDecoder.decode(value);
17 return null;
18 }