多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
TimeServlet.java ~~~ package zyw.cookie; 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 = "TimeServlet",urlPatterns = "/time") public class TimeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.记录访问时间并将其通过cookie加入到响应头中 Date date=new Date(); SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMdd-hh:mm:ss"); String time = simpleDateFormat.format(date); Cookie cookie=new Cookie("time",time); cookie.setMaxAge(60*60);//1小时 response.addCookie(cookie); response.setContentType("text/html;charset=utf-8"); //2.获取客户端浏览器发送过来的cookie数据 Cookie[] cookies=request.getCookies(); String timeValue=null; for (Cookie cookie1:cookies){ if (cookie1.getName().equals("time")){ timeValue =cookie1.getValue(); } } if(timeValue==null){ response.getWriter().write("欢迎您访问我们的网站"); }else { response.getWriter().write("你上次访问网站的时间是:"+timeValue); } } } ~~~ ![](https://box.kancloud.cn/ad2b88ab7a08ce9dbc7a697e7f0bddca_506x107.png)