首页 > 代码库 > cookie包含中文导致的问题
cookie包含中文导致的问题
周五项目测试完毕没问题之后上线,上线之后发现有的账户登录不上
原因为,用来记录追踪用户的cookie中包含cookie。读取,写入时候发生异常。
异常大概是这个样子:
java.lang.IllegalArgumentException: Control character in cookie value or attribute.
at org.apache.tomcat.util.http.CookieSupport.isHttpSeparator(CookieSupport.java:193)
at org.apache.tomcat.util.http.CookieSupport.isHttpToken(CookieSupport.java:217)
at org.apache.tomcat.util.http.ServerCookie.appendCookieValue(ServerCookie.java:186)
at org.apache.catalina.connector..Response.generateCookieString(Response.java:1032)
at org.apache.catalina.connector..Response.addCookie(Response.java:974)
at org.apache.catalina.connector..ResponseFacade.addCookie(ResponseFacade.java:381)
at com.vcfilm.interceptor.service.AutologonService.setCookie(AutologonService.java:168)
at com.vcfilm.interceptor.service.AutologonService.saveLogonInfo(AutologonService.java:129)
at com.vcfilm.interceptor.service.AutologonService.saveLogonInfo(AutologonService.java:139)
at com.vcfilm.wechat.actioncommon.BaseAction.SaveSession(BaseAction.java:45)
at com.vcfilm.wechat.actioncommon.BaseAction.SetMember(BaseAction.java:191)
at com.vcfilm.wechat.member.MemberAction.logincheck(MemberAction.java:364)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
中文需要 URLEncoder.encode. utf-8
可参这篇文章 http://blog.csdn.net/newyear1988/article/details/7817066
加了之后发现还是有问题,写cookie的时候用des加密了,发现取cookie,getVal()之后用解密的时候异常,于是在捕获异常代码块直接返回了getVal()得到的值。
/** * 从cookie中取值 * */ public String getCookieVal(HttpServletRequest request, String key){ Cookie[] cookies= request.getCookies(); if(null != cookies && cookies.length > 0){ for(Cookie c:cookies){ if(c.getName().equalsIgnoreCase(key)){ if(null != c){ try{ return URLDecoder.decode(c.getValue(), "utf-8"); }catch(Exception e){ e.printStackTrace(); return c.getValue(); } } } } } return ""; } /** * 保存值到cookie * */ public void setCookie(String key, String val, int maxAge){ try{ val = URLEncoder.encode(val, "utf-8"); }catch(Exception e){ e.printStackTrace(); } Cookie cookie = new Cookie(key, val); if(maxAge > 0){ cookie.setMaxAge(maxAge); } cookie.setPath("/"); ServletActionContext.getResponse().addCookie(cookie); }
cookie包含中文导致的问题