Cookies cannot store Chinese characters directly. Chinese characters must be encoded as asccii strings.
The code is as follows: |
Copy code |
String str = java.net. URLEncoder. encode (Chinese ); |
Encoded string
The decoded result is as follows:
The code is as follows: |
Copy code |
String str = java.net. URLDecoder. decode (encoded String ); |
Method
Generally, in this process, string transcoding == "saved cookie ==" read cookie == "transcoded =" is displayed.
Step 1: encode the data before writing the cookie
The code is as follows: |
Copy code |
Cookie cookie = new Cookie ("groupMembersList", URLEncoder. encode (groupMembersList, "GBK"); // The default value is temporary Cookie, MaxAge <0 // Cookie. setMaxAge (-1 ); Response. addCookie (cookie ); |
Step 2: read and decode the cookie
The code is as follows: |
Copy code |
<% Cookie [] cookies = request. getCookies (); For (Cookie cookie: cookies ){ If (cookie. getName (). Inclusignorecase ("groupMembersList ")) Request. setAttribute ("group", URLDecoder. decode (cookie. getValue (), "GBK ")); } %> <C: out value = "$ {requestScope. group}"/> |
There is another way
The code is as follows: |
Copy code |
Try { Cookie cookie = new Cookie (name, new String (value. getBytes ("GBK"), "ISO8859-1 ")); Cookie. setDomain (this. domain ); Cookie. setPath ("/"); Cookie. setMaxAge (120*1000 ); Response. addCookie (cookie ); } Catch (Exception e ){ E. printStackTrace (); } |