在用户没有登录时,cookie常用来完成服务器对客户端的省份识别及一些设置的保存。
以下为一个简单的记录用户上次访问时间的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| @WebServlet("/cookieTest") public class CookieTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8");
Cookie[] cookies = request.getCookies(); boolean flag = false; if (cookies != null && cookies.length > 0){ for (Cookie cookie : cookies) { String name = cookie.getName(); if ("lastTime".equals(name)){ flag = true;
String value = cookie.getValue(); value = URLDecoder.decode(value,"utf-8"); response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"<h1>");
Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss"); String str_date = sdf.format(date); str_date = URLEncoder.encode(str_date, "utf-8"); cookie.setValue(str_date); cookie.setMaxAge(60 * 60 * 24 * 30); response.addCookie(cookie);
break; } } } if (cookies == null || cookies.length == 0 || flag == false){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); str_date = URLEncoder.encode(str_date, "utf-8"); Cookie cookie = new Cookie("lastTime",str_date); cookie.setMaxAge(60 * 60 * 24 * 30); response.addCookie(cookie);
response.getWriter().write("<h1>您好,欢迎首次访问<h1>"); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
|