• 【会话技术】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 }

    结果:

  • 相关阅读:
    课后作业-阅读任务-阅读笔记-4
    《团队--学生成绩管理-阶段互评》
    《团队-学生成绩管理-阶段互评》
    团队编程项目作业4-开发文档
    阅读任务--阅读提问-3
    课后作业-阅读任务-阅读笔记3
    课后作业-阅读任务-阅读提问-3
    课后作业-阅读任务-阅读笔记-3
    结对编程项目作业5
    结对编程项目作业4
  • 原文地址:https://www.cnblogs.com/musecho/p/11202502.html
Copyright © 2020-2023  润新知