JavaWeb 入门篇 (5) Cookie 和 Session 详解
Cookie 和 Session 詳解
一、會話的概念
會話可簡單理解為:用戶開一個瀏覽器,點擊多個超鏈接,訪問服務器多個web資源,然后關閉瀏覽器,整個過程稱之為一個會話。
有狀態會話:一個同學來過教室,下次再來教室,我們會知道這個同學曾經來過,這稱之為有狀態會話。
二、會話過程中要解決的一些問題?
每個用戶在使用瀏覽器與服務器進行會話的過程中,不可避免各自會產生一些數據,程序要想辦法為每個用戶保存這些數據。
三、保存會話數據的兩種技術
3.1、Cookie
Cookie的由來
-
首先我們需要介紹一下,在Web開發過程中為什么會引入Cookie。我們知道Http協議是一種無狀態協議,
Web服務器本身不能識別出哪些請求是同一個瀏覽器發出的,瀏覽器的每一次請求都是完全孤立的。
即便在Http1.1支持了持續連接,但當用戶有一段時間沒有提交請求時,連接也會自動關閉。這時,作為Web服務器,
必須采用一種機制來唯一標識一個用戶,同時記錄該用戶的狀態。于是就引入了第一種機制:Cookie機制。 -
Cookie是客戶端技術,程序把每個用戶的數據以cookie的形式寫給用戶各自的瀏覽器。當用戶使用瀏覽器再去訪問服務器中的web資源時,就會帶著各自的數據去。這樣,web資源處理的就是用戶各自的數據了。
-
Cookie是客戶端保存用戶信息的一種機制,用來記錄用戶的一些信息,也是實現Session的一種方式。
-
Cookie保存在客戶端,只能保存字符串對象,不能保存對象類型,需要客戶端瀏覽器的支持:客戶端可以不支持,因為瀏覽器用戶可能會禁用Cookie。
Cookie的定義即基本介紹
Cookie是在瀏覽器訪問WEB服務器的某個資源時,
由WEB服務器在HTTP響應消息頭中附帶傳送給瀏覽器的一個小文本文件。
那么它在以后每次訪問該WEB服務器時,
都會在HTTP請求頭中將這個Cookie回傳給WEB服務器。
它至少含有一個標識該信息的名稱(NAME)和設置值(VALUE)。
一個WEB瀏覽器也可以存儲多個WEB站點提供的Cookie。
每個站點最多存放20個Cookie,每個Cookie的大小限制為4KB。
Cookie的原理
底層的實現原理: WEB服務器通過在HTTP響應消息中增加Set-Cookie響應頭字段將Cookie信息發送給瀏覽器,
瀏覽器則通過在HTTP請求消息中增加Cookie請求頭字段將Cookie回傳給WEB服務器。
Cookie的操作
創建、添加、設置時間、刪除
public Cookie(String name, String value) ; // 創建cookie public void setComment(String purpose); // 設置cookie的描述 public void setMaxAge(int expiry) // 設置 cookie的時間 單位為秒 public String getName() // 獲得存的cookie的名字 public String getValue() // 獲的cookie的值 // 刪除的話 是設置時間為 03.2、Session
概述
- Session是服務器端技術,利用這個技術,服務器在運行時可以為每一個用戶的瀏覽器創建一個其獨享的session對象,由于session為用戶瀏覽器獨享,所以用戶在訪問服務器的web資源時,可以把各自的數據放在各自的session中,當用戶再去訪問服務器中的其它web資源時,其它web資源再從用戶各自的session中取出數據為用戶服務。
- 之前我們介紹的cookie是把用戶的身份信息存在了客戶端,而session說白了就是把用戶的信息保存在了服務端。由于session是保存在了服務端,所以當用戶關閉瀏覽器時session并不會消失。一般session保存在服務器的內存中當然也可以持久化到硬盤或者數據庫中。session的默認過期時間是30分鐘,過期的session會被服務器自動的銷毀。注意如果大量的創建session可能導致服務器的內存溢出。
一、session的創建流程
當客戶端瀏覽器訪問服務器時,服務器會先檢查該請求是否攜帶一個叫JESESSIONID的cookie,如果存在會根據JESESSIONID的cookie值獲取存放在服務器端的session值;如果不存在會新建一個session然后把sessionId寫到cookei中返回給瀏覽器,下次瀏覽器訪問時就會攜帶這個cookie。
小demo
-
測試1 第一次登錄不展示名字 第二次會展示存進去的值。
- public class TestSessionServlet extends HttpServlet{private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {HttpSession session = request.getSession();response.setCharacterEncoding("utf-8");response.setHeader("content-type","text/html;charset=UTF-8");PrintWriter writer = response.getWriter();String loginName = (String) session.getAttribute("loginName");String sessionId = session.getId();if(StringUtils.isEmpty(loginName)){session.setAttribute("loginName","張三");writer.println("session中沒有值!");}else{writer.println("loginName="+loginName);}writer.println("sessionId="+sessionId);writer.close();}
}
JavaWeb 中 Session 模擬登錄、攔截
表單頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>login</title> </head> <body> <form action="${pageContext.request.contextPath}/sessionLogin" method="post">用戶名:<input name="username" type="text">密碼:<input name="password" type="password"><input type="submit" value="Login"> </form> </body> </html>里面用到的User類
/*** @author crush*/ public class User {private String username;private String password;public User(String username, String password) {this.username = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;} }處理登錄的Servlet
/*** @author crush* 實現自動登錄*/ @WebServlet("/sessionLogin") public class Login extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 開啟sessionHttpSession session = req.getSession();// 獲取登錄的參數String username = req.getParameter("username");String password=req.getParameter("password");// 設置字符編碼resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();// 判斷用戶名和密碼是否正確if(username.equals("admin")&&password.equals("123456")){// 存sessionsession.setAttribute("user",new User(username,password));session.setMaxInactiveInterval(200);writer.print("恭喜你登錄成功!!!");}else{System.out.println("賬號或密碼錯誤");resp.sendRedirect("/login.jsp");}} }mian2請求 測試是否登錄的請求
/** * @author crush*/ @WebServlet("/main2") public class Main extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession();User user =(User) session.getAttribute("user");// 設置字符編碼resp.setContentType("text/html;charset=utf-8");if(user==null){// 沒有登錄會轉向登錄頁面resp.sendRedirect("/login.jsp");}else{req.setAttribute("success","恭喜你做出了登錄的小Demo!!!");req.getRequestDispatcher("/hello.jsp").forward(req,resp);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);} }Hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>hello</title> </head> <body> ${success} <br> </body> </html>
自言自語
簡單的一天。
總結
以上是生活随笔為你收集整理的JavaWeb 入门篇 (5) Cookie 和 Session 详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: github push报 Unable
- 下一篇: JavaWeb入门篇(6) 实现字符过滤