Today, we have completed a function to record user names with cookies. We did not consider the impact of user names in Chinese. During the test, I used a Chinese character to log on and found an error. The error message is as follows:
Java. Lang. illegalargumentexception: Control Character in cookie value, consider base64 encoding your value
After I checked it online, I realized that it was a transcoding problem. The solution is as follows;
In J2EE doc, cookies only support ASCII characters and cannot contain commas (,) or semicolons,
Blank. Or start with $. The name cannot be changed after it is created. If you want to store Chinese characters, urlecode is used first. Decode is used to decode the stored and retrieved characters!
Solution:
// Create a cookie. Considering that the user name may be Chinese, use urlencoder. encode (string, string) encoding to decode the cookie during retrieval.
Cookie cookiename = new cookie ("uname", urlencoder. encode (uname, "UTF-8 "));
// Another encode (string, string) method is out of date. This method is not recommended for reference.
// Considering that the entered user name may have Chinese characters, urlencoder encoding has been used before. urldecoder decoding is required here.
String unameval = urldecoder. Decode (cookie. getvalue (), "UTF-8 ");
The Code is as follows:
Import java.net. urlencoder;
Cookie c = new cookie ("name", urlencoder. encode (pname ));
C. setmaxage (30 );
Response. addcookie (C );
If (cookies! = NULL ){
For (INT I = 0; I <cookies. length; I ++ ){
If (Cookies [I]. getname (). Equals ("love "))
Plove = urldecoder. Decode (Cookies [I]. getvalue ());}
}