Look at the time, see the book on the use of cookies to save information, see the book cited examples are English key value pairs, I think Chinese is not the same? A try is not the same. Nonsense not much to say, directly on the code:
For example, there are addcookie.jsp code as follows:
Copy Code code as follows:
<title> Add cookie</title>
<body>
<%
String name = Request.getparameter ("name");
Cookie C = new Cookie ("username", name);
C.setmaxage (3600);
Response.addcookie (c);//Add Cookie
%>
</body>
Enter the Localhost:8080/webdemo/addcookie.jsp?name= test name in the address bar to complete the cookie addition.
The following is the removal of the cookie, getcookie.jsp code is as follows:
Copy Code code as follows:
<title> Add cookie</title>
<body>
<%
cookie[] cookies = request.getcookies ()//Remove Cookies
for (cookie cc:cookies)//traversal to find the corresponding cookie
{
if (Cc.getname (). Equals ("username"))
{
Out.println (Cc.getvalue ());
}
}
%>
</body>
However, when you enter localhost:8080/webdemo/getcookie.jsp in the address bar, an error is found, because the encoding is based on the requirement in RFC 2109 that only ASCII encoding can be included in the cookie.
Then you can only encode the Chinese when you set up cookies. The improved code is as follows:
Copy Code code as follows:
<%
String name = Request.getparameter ("name");
byte[] Rawname = name.getbytes ("iso-8859-1");
String strName = new String (Rawname, "GB2312");//Get parameter in Chinese string form
Cookie C = new Cookie ("username", Urlencoder.encode (StrName, "UTF-8"));
C.setmaxage (3600);
Response.addcookie (c);
%>
<%
cookie[] cookies = request.getcookies ();
for (Cookie cc:cookies)
{
if (Cc.getname (). Equals ("username"))
{
String str = urldecoder.decode (Cc.getvalue (), "UTF-8");//decoding
Out.println (str);
}
}
%>
Nowhere else is the problem, as in the following code, someone does something different.
Copy Code code as follows:
byte[] Rawname = name.getbytes ("iso-8859-1");
String strName = new String (Rawname, "GB2312");//Get parameter in Chinese string form
Cookie C = new Cookie ("username", Urlencoder.encode (StrName, "UTF-8"));
I searched a lot of information, there is only a piece of code, such as: cookie C = new Cookie ("username", Urlencoder.encode ("Monkey King", "UTF-8"));
Placing Chinese directly in the parameter position of the Encode method may appear to be directly in the Name=request.getparameter ("name"), and then the cookie c = new Cookie ("username") is invoked. Urlencoder.encode (name, "UTF-8")); code snippet, it looks like there is no wrong, but I found in practice will produce garbled, I use Firefox browser, and then I added two pieces of code, is: byte[] Rawname = Name.getbytes ("iso-8859-1");
String strName = new String (Rawname, "GB2312"); there is no garbled, specific why the reason for this, I do not know, I do not understand which great God can explain.