提示:Cookie中保存中文只能編碼,一般使用UTF-8編碼即可。不推薦使用GBK等中文編碼,
因爲瀏覽器不一定支持,而且JavaScript也不支持GBK編碼
<%@page language="java"import="java.util.*"pageEncoding="UTF-8"isErrorPage="true"%>
<jsp:directive.pageimport="java.net.URLEncoder"/>
<jsp:directive.pageimport="java.net.URLDecoder"/>
<%
Cookie cookie = new Cookie(URLEncoder.encode("姓名",
"UTF-8"),URLEncoder.encode("黎明","UTF-8"));
response.addCookie(cookie);
%>
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma"content="no-cache">
<meta http-equiv="cache-control"content="no-cache">
<meta http-equiv="expires"content="0">
<meta http-equiv="keywords"content="keyword1,keyword2,keyword3">
<meta http-equiv="description"content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</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.print(cookieName+"="+cookieValue+";<br/>");
}
}else{
out.print("Cookie已經寫入客戶端,請刷新頁面");
}
%>
</body>
</html>