package com.home; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet(name = "CookieWork", urlPatterns = "/cookie01") public class CookieWork extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置响应的消息体的数据格式以及编码 resp.setContentType("text/html;charset=utf-8"); //1.获取所有Cookie Cookie[] cookies = req.getCookies(); boolean a = false; if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { String name = cookie.getName(); if ("lastTime".equals(name)) { a = true; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(date); cookie.setValue(format); cookie.setMaxAge(60 * 60 * 24 * 30 * 12); resp.addCookie(cookie); String value = cookie.getValue(); resp.getWriter().write("欢迎回来,您上次访问时间为:" + value + ""); break; } } } if (cookies == null || cookies.length == 0 || a == false) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(date); Cookie cookie = new Cookie("lastTime", format); cookie.setMaxAge(60 * 60 * 24 * 30 * 12); resp.addCookie(cookie); resp.getWriter().write("您好,欢迎您首次访问"); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)