Two types of schemes, recommended the second option:
One:
package com.servlet; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SecondServlet */ //@WebServlet("/SecondServlet") public class Cookies extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Cookies() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码问题 response.setContentType("text/html;charset=utf-8"); //本次访问时间 String time = new Date().toLocaleString(); //shez设置时间cookie response.setHeader("Set-cookie", " Time = " + Time); // time when the acquisition was last accessed String = oldtime request.getHeader ( " Cookie " ); // accessed the last time back to the browser . Response.getWriter () the Write ( " Last access time is: " + oldtime); } protected void the doPost (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException { the doGet (Request, Response); } }
two:
Note: If using tomcat8, then this method can not have spaces in a cookie, it will error if there are spaces
package com.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SecondServlet */ //@WebServlet("/SecondServlet") public class Cookies extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Cookies() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码问题 response.setContentType("text/html;charset=utf-8"); //本次访问时间 Date date = new Date(); SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss"); String time = smf.format(date); System.out.println(time); //shez设置时间cookie Cookie cookie = new Cookie("time",time); response.addCookie(cookie); //获取上次访问时的时间 Cookie[] cookies = request.getCookies(); if (cookies!=null) { for(Cookie cookie2:cookies){ if ("time".equals (cookie2.getName ())) { // returns the browser to the last access time response.getWriter () Write (. " last access time is: " + cookie2.getValue ()); } } } } protected void the doPost (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException { the doGet (Request, Response); } }