How to write Chinese code to cookie in JSP

Time:2020-4-8

In JSP, a little bit of Chinese processing is not good, and there may be garbled code. Let me introduce to you how to write Chinese implementation program to cookie in JSP for your reference.

Cookies cannot be stored directly in Chinese. Chinese must be encoded as asccii string. You can do this (http://www.javaweb.cc collection and sorting)

The code is as follows
String STR = java.net.urlencoder.encode (Chinese);

Get the encoded string
Decode as follows:
The code is as follows
String STR = java.net.urldecoder.decode (encoded string);

Specific methods

Generally, such a process string transcoding = = “store cookie = =” read cookie = = “transcoding = =” display

Step 1: code the cookie first

The code is as follows
Cookie cookie = new cookie (“groupmemberslist”, urlencoder. Encode (groupmemberslist, “GBK”)); / / the default is temporary cookie, maxage < 0
//cookie.setMaxAge(-1);
response.addCookie(cookie);

Step 2: read the cookie and decode it

The code is as follows
<%
Cookie[] cookies=request.getCookies();
for(Cookie cookie:cookies){
if(cookie.getName().equalsIgnoreCase(“groupMembersList”))
request.setAttribute(“group”,URLDecoder.decode(cookie.getValue(),”GBK”));
}
%>

<c:out value=”${requestScope.group }”/>

There’s another way

The code is as follows
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();
}