Unicode编码:保存中文cookie

       中文和英文字符不同,中文属于Unicod字符,在内存中站4个字符,而英文属于ASCII字符,内存中只占2个字符。Cookie中使用Unicode字符时需要对Unicode字符进行编码,否则会乱码。编码使用java.net.URLEncoder类的encode(String str,String encoding)方法,解码使用java.net.URLDecoder类的decode(String str,String encoding)方法。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  %>
<jsp:directive.page import="java.net.URLEncoder"/>
<%@ page import="java.net.URLDecoder" %>
<%
    Cookie cookie =new Cookie(URLEncoder.encode("姓名","UTF-8"),
            URLEncoder.encode("刘京华", "UTF-8")
            );
    response.addCookie(cookie);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
        if(request.getCookies()!=null){
            for(Cookie cc:request.getCookies()){
                String cookieName=URLDecoder.decode(cc.getName(), "UTF-8");
                String cookieValue=URLDecoder.decode(cc.getValue(), "UTF-8");
                out.println(cookieName+"="+cookieValue);
            }
        }else{
            out.println("Cookie 已经写入客户端,请刷新");
        }
    
    %>
</body>
</html>

结束语:Cookie保存中文只能编码,一般使用UTF-8编码即可。不推荐使用GBK等中文编码,因为浏览器不一定支持,而且javascript也不支持GBK编码。

原文地址:https://www.cnblogs.com/gengaixue/p/6646751.html