码迷,mamicode.com
首页 > 其他好文 > 详细

通过servlet使用Cookie获取用户上次访问时间

时间:2016-05-13 20:38:36      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

解决tomcat使用Cookie中文乱码问题,javaWeb新手

 1 public class CookieTest extends HttpServlet {
 2 
 3 
 4     public void doGet(HttpServletRequest request, HttpServletResponse response)
 5             throws ServletException, IOException {
 6         
 7         String currentDate = mCurrentDate();
 8         String date = null;
 9         
10         Cookie[] cookies = getCookies(request);
11         
12         if(cookies == null){
13             date = "欢迎访问小站,当前时间:" + currentDate;
14         } else {
15             for (Cookie cookie : cookies) {
16                 //解码URLDecoder.decode(cookies[i].getName(),"utf-8")
17                 System.out.println(URLDecoder.decode(cookie.getName(),"utf-8") 
18                         +  "=" + (URLDecoder.decode(cookie.getValue(),"utf-8")));
19                 
20                 if("LastTime".equals(URLDecoder.decode(cookie.getName(),"utf-8"))){
21                     date = "上次访问时间:" + URLDecoder.decode(cookie.getValue(),"utf-8");
22                 } else {
23                     date = "欢迎访问小站,当前时间:" + currentDate;
24                 }
25             }
26             
27             //编码URLEncoder.encode(currentDate, "utf-8");
28             setCookie(URLEncoder.encode(currentDate, "utf-8"), response);
29         }
30         
31         response.setContentType("text/html;charset=utf-8");
32         response.getOutputStream().write(date.getBytes("utf-8"));
33 
34     }
35     
36     /**
37      * 获取当前时间
38      * @return
39      */
40     public String mCurrentDate(){
41         Date date = new Date();
42         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
43         return dateFormat.format(date);
44     }
45     
46     /**
47      * 设置cookie
48      * @param currentDate 当前时间
49      * @param response HttpServletResponse
50      */
51     public void setCookie(String currentDate,HttpServletResponse response){
52         Cookie cookie = new Cookie("LastTime", null);
53         cookie.setMaxAge(60*60*24*30);
54         cookie.setValue(currentDate);
55         response.addCookie(cookie);
56     }
57     
58     /**
59      * 获取cookie
60      * @param request HttpServletRequest
61      * @return Cookie集合
62      */
63     public Cookie[] getCookies(HttpServletRequest request){
64         return request.getCookies();
65     }
66 }

 

通过servlet使用Cookie获取用户上次访问时间

标签:

原文地址:http://www.cnblogs.com/sdwfqin/p/5490918.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!