Solution to Chinese garbled characters written to cookies in jsp

Source: Internet
Author: User

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

Related Article

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.