1、新建一个项目:
2、在src中建立一个servlet包,包中新建一个servlet
3、
4、servlet文件中写代码:
package LastTimeServlet; 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; public class LastTimeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Date date=new Date();====================================================================创建一个date对象 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-DD hh:mm:ss");========================用SimpleDateFormat改变日期格式 String time=sdf.format(date); Cookie cookie=new Cookie("lasttime",time);=====================创建Cookie对象,记录当前最新访问时间 cookie.setMaxAge(60*10);======================================= response.addCookie(cookie); String lasttime=null; Cookie[] cookies=request.getCookies(); if(cookies!=null){ for(Cookie c:cookies){ if(c.getName().equals("lasttime")){} lasttime=c.getValue(); } } //解决中文乱码 response.setContentType("text/html;charset=utf-8"); if(lasttime==null){ response.getWriter().write("你是第一次访问"); }else{ response.getWriter().write("距上次访问的时间是"+lasttime); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }