Java后端Cookie實(shí)現(xiàn)(時(shí)間戳)代碼實(shí)例
我們來簡單實(shí)現(xiàn)一個(gè)cookie。
一、簡單介紹
Cookie 是一些數(shù)據(jù), 存儲(chǔ)于你電腦上的文本文件中。
當(dāng) web 服務(wù)器向?yàn)g覽器發(fā)送 web 頁面時(shí),在連接關(guān)閉后,服務(wù)端不會(huì)記錄用戶的信息。
Cookie 的作用就是用于解決 '如何記錄客戶端的用戶信息':
當(dāng)用戶訪問 web 頁面時(shí),他的名字可以記錄在 cookie 中。 在用戶下一次訪問該頁面時(shí),可以在 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('您上一次訪問時(shí)間為:'); 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注冊(cè)和映射
<!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ù)組為空 不顯示登陸時(shí)間
按理說應(yīng)該會(huì)顯示else里面的內(nèi)容first time come to this website!
但是顯示的是
只是因?yàn)橄旅娴牡诙垐D 是因?yàn)闉g覽器(我的是edge瀏覽器)默認(rèn)還有一個(gè)cookie
也就是說我們第一次在執(zhí)行頁面(如果是從8080頁面輸入url跳轉(zhuǎn)的)時(shí) 有別的cookie存在
第二次才會(huì)顯示
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)3. Spring如何使用xml創(chuàng)建bean對(duì)象4. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法5. python實(shí)現(xiàn)PolynomialFeatures多項(xiàng)式的方法6. Java程序的編碼規(guī)范(6)7. python 利用toapi庫自動(dòng)生成api8. python實(shí)現(xiàn)在內(nèi)存中讀寫str和二進(jìn)制數(shù)據(jù)代碼9. Android Studio設(shè)置顏色拾色器工具Color Picker教程10. Python paramiko 模塊淺談與SSH主要功能模擬解析
