添加cookie是response对象的一个重要功能,可以通过request对象接受cookie的值,但是cookie中若有中文字符容易出现错误或乱码,解决如下:
添加cookie:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!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=UTF-8">
- <title>set cookie</title>
- </head>
- <body>
- <%
- String str = "这是中文的cookie值";
- Cookie c = new Cookie("str",java.net.URLEncoder.encode(str));
- c.setMaxAge(24*3600);
- //向客户端添加cookie对象
- response.addCookie(c);
- %>
- </body>
- </html>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!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=UTF-8">
- <title>get-cookie-value -- by www.phpddt.com</title>
- </head>
- <body>
- <%
- request.setCharacterEncoding("utf-8");
- Cookie[] cookies = request.getCookies();
- for(Cookie c : cookies)
- {
- //如果有名为str的cookie值,则是要需找的
- if(c.getName().equals("str"))
- {
- out.print(java.net.URLDecoder.decode(c.getValue()));
- }
- }
- %>
- </body>
- </html>