会话技术Cookie技术 案例:访问时间
Posted musecho
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了会话技术Cookie技术 案例:访问时间相关的知识,希望对你有一定的参考价值。
创建时间:6.30
代码:
1 package cookie; 2 3 import java.io.IOException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.Cookie; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 public class LastAccessTimeServlet extends HttpServlet 14 15 protected void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException 17 18 Date date = new Date(); 19 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd/hh:mm:ss"); 20 String currentTime = format.format(date); 21 22 Cookie cookie = new Cookie("lastAccessTime",currentTime); 23 cookie.setMaxAge(60*10*500); 24 response.addCookie(cookie); 25 26 String lastAccessTime = null; 27 Cookie[] cookies = request.getCookies(); 28 if(cookies!=null) 29 for(Cookie coo : cookies) 30 if("lastAccessTime".equals(coo.getName())) 31 lastAccessTime = coo.getValue(); 32 33 34 35 36 response.setContentType("text/html;charset=UTF-8"); 37 if(lastAccessTime==null) 38 response.getWriter().write("您第一次访问"); 39 else 40 response.getWriter().write("上次访问时间:"+lastAccessTime); 41 42 43 44 45 protected void doPost(HttpServletRequest request, HttpServletResponse response) 46 throws ServletException, IOException 47 doGet(request, response); 48 49
结果:
以上是关于会话技术Cookie技术 案例:访问时间的主要内容,如果未能解决你的问题,请参考以下文章