cookie案例-顯示使用者上次訪問網站的時間

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   os   

 1 package cn.itcast.cookie; 2  3 import java.io.IOException; 4 import java.io.PrintWriter; 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 CookieDemo extends HttpServlet {14 15     public void doGet(HttpServletRequest request, HttpServletResponse response)16             throws ServletException, IOException {17 18         response.setCharacterEncoding("UF-8");19         response.setContentType("text/html;charset=UTF-8");20         21         PrintWriter out = response.getWriter();22         out.print("您上次訪問的時間是:");23         24         //獲得使用者的時間cookie25         Cookie cookies[] = request.getCookies();26         for(int i=0;cookies!=null&&i<cookies.length;i++){27             if(cookies[i].getName().equals("lastAccessTime")){28                 long cookieValue = Long.parseLong(cookies[i].getValue());29                 Date date = new Date(cookieValue);30                 31                 out.print(date.toLocaleString());32                 33             }34         }35         36         //給用使用者會送最新的訪問時間。37         Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");38         cookie.setMaxAge(1*30*24*3600);39         cookie.setPath("/ServletDemo");40         41         response.addCookie(cookie);42         43     }44 45     46     public void doPost(HttpServletRequest request, HttpServletResponse response)47             throws ServletException, IOException {48 49         50     }51 52 }
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.