日期:2014-05-17 浏览次数:20881 次
public class TestCookie extends HttpServlet {
public void service(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
if(cookies == null) {
//添加cookie操作
Cookie cookie = new Cookie("myCookie1",
URLEncoder.encode("cookie1的内容", "utf-8"));
cookie.setPath("/testCookieAndSession/TestCookie");
//添加一个设置时间的Cookie
Cookie cookie2 = new Cookie("myCookie2",
URLEncoder.encode("cookie1的内容", "utf-8"));
cookie2.setMaxAge(30);
response.addCookie(cookie);
response.addCookie(cookie2);
out.print("Cookie已经生成");
} else {
for(Cookie c: cookies) {
String name = c.getName();
String value = URLDecoder.decode(c.getValue(), "utf-8");
out.println("name=" + name + "<br/>"
+ "value=" + value + "<br/>"
);
}
}
out.close();
}