用Cookie实现访问浏览器显示上次访问时间。 那就先来说说Cookie,Cookie这个技术并不是Java特有的,它是由W3C这个组织制定一个标准,这个技术主要应用在浏览器中。 当用户在访问一个网站时,网站后台会以Cookie的形式将用户对网站的一些操作数据保存到浏览器中,这样当用户下次使用这个浏览器访问这个网站的时候就会将这些数据放在请求中给浏览器发送过去。 首先是创建Cookie,当在new这个类的时候需要两个参数,类似于key-value的形式,这样服务器就会将这组key-value值保存到浏览器中。
//从用户的请求中获取到所有的Cookie信息 Cookie[] cookies = req.getCookies();当获取到用户请求中的所有Cookie中的时候,需要找到我们自己需要在浏览器中保存用户上次访问时间的那个Cookie
//定义了一个findCookie方法将获取到的这个cookies数组以及我们需要找的key(value)传递过去 Cookie c = findCookie(cookies ,"time"); //findCookie方法 private Cookie findCookie(Cookie[] cookies,String time) { //首先判断这个cookies数组是否为空,为空则返回null if(cookies==null){ return null; } //循环遍历cookies数组 for (Cookie cookie : cookies) { //通过Cookie类中的getName方法获取到每一组Cookie中的key和我们需要找的time进行比较 if(cookie.getName().equals(time)){ //当找到key为time的cookie时返回这个 return cookie; } } //当循环遍历结束,说明cookies这个数组中有cookie但是没有我们想要的,所以返回null return null; }当拿到返回的值时,通过判断就可以进行下一步的操作
//获取当前系统的毫秒值 long millis = System.currentTimeMillis(); //创建一个Date对象 Date d =new Date(); //判断findCookie返回的是否为空 if(c==null){ //为空则第一次访问,将当前系统的毫秒值给time c = new Cookie("time",millis+""); resp.getWriter().write("第一次访问设置time"); }else{ //当findCookie返回的是否不为空,说明不是第一次访问,则拿到time对应的value值 String value = c.getValue(); //将拿到的value也就是上次访问浏览器的时间设置为当前时间 d.setTime(Long.parseLong(value)); //格式化Date日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM--dd HH:mm:ss"); String s = sdf.format(d); //最后需要将当前系统的毫秒值设置给time,下次访问时就可以拿到这次访问的时间 c.setValue(millis+""); //并且给客户端响应你上册访问的事件 resp.getWriter().write("你上次访问的时间是"+s); } //调用Cookie中的setMaxAge方法设置这组Cookie保存的时间,这里是保存一天 c.setMaxAge(60*60*24); //最后把设置的cookie添加到浏览器的Cookie中 resp.addCookie(c);完整代码及演示图片
@WebServlet(urlPatterns = "/time") public class GetTime extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset = utf-8"); Cookie[] cookies = req.getCookies(); Cookie c = findCookie(cookies ,"time"); long millis = System.currentTimeMillis(); Date d =new Date(); if(c==null){ c = new Cookie("time",millis+""); resp.getWriter().write("第一次访问设置time"); }else{ String value = c.getValue(); d.setTime(Long.parseLong(value)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM--dd HH:mm:ss"); String s = sdf.format(d); c.setValue(millis+""); resp.getWriter().write("你上次访问的时间是"+s); } c.setMaxAge(60*60*24); resp.addCookie(c); } private Cookie findCookie(Cookie[] cookies,String time) { if(cookies==null){ return null; } for (Cookie cookie : cookies) { if(cookie.getName().equals(time)){ return cookie; } } return null; } }演示图片
