javaee學習-Cookie使用範例

來源:互聯網
上載者:User

標籤:value   tps   local   etc   ast   編碼   parse   utf-8   type   

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 設定伺服器端以UTF-8編碼進行輸出
response.setCharacterEncoding("UTF-8");
// 設定瀏覽器以UTF-8編碼進行接收,解決中文亂碼問題
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 擷取瀏覽器訪問訪問伺服器時傳遞過來的cookie數組
Cookie[] cookies = request.getCookies();
// 如果使用者是第一次訪問,那麼得到的cookies將是null
if (cookies != null) {
out.write("您上次訪問的時間是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("lastAccessTime")) {
Long lastAccessTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastAccessTime);
out.write(date.toLocaleString());
}
}
} else {
out.write("這是您第一次訪問本站!");
}

// 使用者訪問過之後重新設定使用者的訪問時間,儲存到cookie中,然後發送到用戶端瀏覽器
Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()
+ "");// 建立一個cookie,cookie的名字是lastAccessTime
// 將cookie對象添加到response對象中,這樣伺服器在輸出response對象中的內容時就會把cookie也輸出到用戶端瀏覽器
response.addCookie(cookie);
}

javaee學習-Cookie使用範例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.