SoFunction
Updated on 2025-04-07

jsp using cookies to store Chinese examples

When I was reading J2EE, I saw that when I was talking about using cookies to save information, and when I saw that the examples mentioned in the book were all key-value pairs in English, I wonder if it is the same in Chinese? I tried it and it turned out to be different. Without further ado, just upload the code:

For example, there is code as follows:

Copy the codeThe code is as follows:

<html xmlns="http:///1999/xhtml">
<head>
<title>Add cookies</title>
</head>
<body>
<%
String name = ("name");
Cookie c = new Cookie("username",name);
(3600);
(c);//Add cookies
%>
</body>
</html>

Enter localhost:8080/webDemo/?name= test name in the address bar to complete the cookie addition.

The following is the cookie, the code is as follows:

Copy the codeThe code is as follows:

<html xmlns="http:///1999/xhtml">
<head>
<title>Add cookies</title>
</head>
<body>
<%
Cookie[] cookies = ();//Remove cookies
for(Cookie cc:cookies)//Travel to find the corresponding cookie
{
    if(().equals("username"))
    {
        (());
    }
}
%>
</body>
</html>

However, when entering localhost:8080/webDemo/ in the address bar, it is found that this situation is due to encoding reasons. According to the provisions in RFC 2109, only ASCII encoding can be included in the cookie.

Then you can only encode Chinese when setting cookies. The code is improved as follows:

Copy the codeThe code is as follows:

<%
String name = ("name");
byte[] rawName = ("ISO-8859-1");
String strName = new String(rawName,"GB2312");//Get the Chinese string form of the parameter
Cookie c = new Cookie("username",(strName,"UTF-8"));
(3600);
(c);
%>
<%
Cookie[] cookies = ();
for(Cookie cc:cookies)
{
    if(().equals("username"))
    {
String str = ((),"UTF-8");//Decode
        (str);
    }
}
%>

There is no big problem elsewhere, but in the following code, someone did something different.

Copy the codeThe code is as follows:

byte[] rawName = ("ISO-8859-1");
String strName = new String(rawName,"GB2312");//Get the Chinese string form of the parameter
Cookie c = new Cookie("username",(strName,"UTF-8"));

I searched for a lot of information, all of which only had a piece of code, such as: Cookie c = new Cookie("username",("Sun Wukong","UTF-8"));

Put the Chinese directly in the parameter position of the encode method, and it seems that you can call the above cookie c = new cookie("username",(name,"UTF-8")); code segment, it seems to be correct, but in practice, I found that it will produce garbled code. I used Firefox browser, and then I added two pieces of code, namely: byte[] rawName = ("ISO-8859-1");
String strName = new String(rawName,"GB2312"); did not produce garbled code. I don't know why this is the case yet, and I don't know which master can explain it.