Java后端Cookie實(shí)現(xiàn)(時間戳)代碼實(shí)例
我們來簡單實(shí)現(xiàn)一個cookie。
一、簡單介紹
Cookie 是一些數(shù)據(jù), 存儲于你電腦上的文本文件中。
當(dāng) web 服務(wù)器向?yàn)g覽器發(fā)送 web 頁面時,在連接關(guān)閉后,服務(wù)端不會記錄用戶的信息。
Cookie 的作用就是用于解決 '如何記錄客戶端的用戶信息':
當(dāng)用戶訪問 web 頁面時,他的名字可以記錄在 cookie 中。 在用戶下一次訪問該頁面時,可以在 cookie 中讀取用戶訪問記錄(博客園cookie界面)
二、簡單實(shí)現(xiàn)
0.maven引入依賴
servlet和jsp的依賴
1.java代碼編寫
package com.lei;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;import java.util.Date;public class CookieDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding('utf-16'); resp.setCharacterEncoding('utf-16'); PrintWriter out =resp.getWriter(); Cookie[] cookies=req.getCookies(); if(cookies!=null) { out.write('您上一次訪問時間為:'); for(int i=0;i< cookies.length;i++) {Cookie cookie=cookies[i];if(cookie.getName().equals('lastLoginTime')){ long lastLoginTime=Long.parseLong(cookie.getValue()); Date date=new Date(lastLoginTime); out.write(date.toString());} } } else{ out.write('first time come to this website!'); } Cookie cookie=new Cookie('lastLoginTime',System.currentTimeMillis()+''); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
2.設(shè)置web-xml里面加入 servlet注冊和映射
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd' ><web-app xmlns='http://xmlns.jcp.org/xml/ns/javaee' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd' version='4.0' metadata-complete='true'><servlet> <servlet-name>cookie</servlet-name> <servlet-class>com.lei.CookieDemo01</servlet-class></servlet><servlet-mapping> <servlet-name>cookie</servlet-name> <url-pattern>/cookie</url-pattern></servlet-mapping></web-app>
三、運(yùn)行效果
第一次cookie數(shù)組為空 不顯示登陸時間
按理說應(yīng)該會顯示else里面的內(nèi)容first time come to this website!
但是顯示的是
只是因?yàn)橄旅娴牡诙垐D 是因?yàn)闉g覽器(我的是edge瀏覽器)默認(rèn)還有一個cookie
也就是說我們第一次在執(zhí)行頁面(如果是從8080頁面輸入url跳轉(zhuǎn)的)時 有別的cookie存在
第二次才會顯示
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XHTML 1.0:標(biāo)記新的開端2. html清除浮動的6種方法示例3. ASP腳本組件實(shí)現(xiàn)服務(wù)器重啟4. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案5. xml中的空格之完全解說6. ASP基礎(chǔ)入門第三篇(ASP腳本基礎(chǔ))7. 怎樣才能用js生成xmldom對象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?8. css進(jìn)階學(xué)習(xí) 選擇符9. CSS3中Transition屬性詳解以及示例分享10. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法
