cookie它是用户访问Web服务器时,服务器在用户硬盘上存放的信息。
1.使用Servlet实现cookie
@WebServlet("/CookieServlet") public class CookieServlet extends HttpServlet { private static final long serialVersionUID = 1L; private int count1; private int count2; public CookieServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = new Cookie("cookieName" +count1++, "cookieValue" + count2++); cookie.setMaxAge(15); response.addCookie(cookie); Cookie[] cookies = request.getCookies(); if (cookies == null) { return; } for(Cookie cook : cookies){ System.out.println("cookie name: " +cook.getName()); System.out.println("cookie value: " +cook.getValue()); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
cookie的设值方法: response.addCookie(cookie)
cookie的取值方法:Cookie[] cookies = request.getCookies();
2. 使用Jsp实现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>Insert title here</title> </head> <body> <%! int count1 = 0; int count2 = 0; %> <% Cookie cookie = new Cookie("cookieName"+ count1++, "cookieValue" +count2++); cookie.setMaxAge(15); response.addCookie(cookie); %> <% Cookie[] cookies = request.getCookies(); if(null == cookie){ return; } for(Cookie c : cookies){ %> <p> <b>cookie name: <%= c.getName() %><b><br> <b>cookie value: <%= c.getValue() %></b> </p> <% } %> </body> </html>