Cookie
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*创建cookie,设定一个星期内有效,并新增至响应之中*/
- Cookie cookie = new Cookie("user","黄"); // 创建cookie
- cookie.setMaxAge(7*24*60*60); //设置生命周期
- response.addCookie(cookie); // 执行添加后就从response里覆盖修改了
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Cookie</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Cookie</h1>");
out.println("<a href='getCookie.jsp'>获取cookie</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Cookie</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Cookie</h1>");
Cookie[] cookies= request.getCookies(); //getCookies()方法取得Cookie
if(cookies!=null) {
for(Cookie c : cookies) {
String name = c.getName();
String value = c.getValue();
out.println("<h1>Cookie的名称:"+name+"值:"+value+"</h1>");
}
}
out.println("</body>");
out.println("</html>");
out.close();
}