Solution to server 500 error when the user login name is in Chinese

Source: Internet
Author: User

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 ());}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.