關(guān)于B/S結(jié)構(gòu)系統(tǒng)的會話機制
三種域?qū)ο?/h4>
這三個域?qū)ο蟮拇笮£P(guān)系: request < session < application, 盡量使用小的域
- request 請求域(請求級別的), 對應(yīng)的類名:HttpServletRequest
- session會話域(用戶級別的), 對應(yīng)的類名:HttpSession
- application應(yīng)用域(項目級別的,所有用戶共享的)對應(yīng)的類名:ServletContext
- 三個域?qū)ο蠖加腥齻€公共的方法: setAttribute(向域當中綁定數(shù)據(jù)), getAttribute(從域當中獲取數(shù)據(jù)), removeAttribute(刪除域當中的數(shù)據(jù))
HttpSession
一個會話當中包含多次請求(一次會話對應(yīng)N次請求)
- 一次會話對應(yīng)服務(wù)器端的session對象: 用戶打開瀏覽器進行的一系列操作然后最終將瀏覽器關(guān)閉的整個過程,可以認為是一次會話
- 一次請求對應(yīng)服務(wù)器端的request對象:用戶在瀏覽器上點擊了一下然后到頁面停下來,可以認為是一次請求
jarkata.servlet.http.HttpSessionsession對象用來保存會話狀態(tài)(用戶登錄成功是一種登錄成功的狀態(tài),使用session對象可以保留這種會話狀態(tài))
- 因為HTTP協(xié)議是一種無狀態(tài)協(xié)議 ,請求的瞬間B和S是連接的,但是請求結(jié)束之后,連接就斷了,這樣可以降低服務(wù)器的壓力
- 由于B和S斷開了所以服務(wù)器是不知道瀏覽器什么時候關(guān)閉的, 就不會銷毀session對象
- session機制屬于B/S結(jié)構(gòu)的一部分是一個規(guī)范, 不同的語言開發(fā)web項目對這種會話機制都有實現(xiàn)
request請求域(HttpServletRequest), application應(yīng)用域(ServletContext)不被用來保存會話狀態(tài)
- reques對象是瀏覽器發(fā)起請求的時候創(chuàng)建,請求結(jié)束之后銷毀, 請求域的作用域太小并且保存的數(shù)據(jù)在下次請求中就不能拿來使用
- ServletContext對象是服務(wù)器啟動的時候創(chuàng)建,服務(wù)器關(guān)閉的時候銷毀,應(yīng)用域的作用域太大
HttpSession對象創(chuàng)建和銷毀的時機(js內(nèi)置一個session對象并有其對應(yīng)的Cookie對象(JSESSIONID=xxx), 不需要等到服務(wù)器生成返回就可以在jsp頁面中使用)
- 用戶發(fā)起第一次請求, 服務(wù)器端獲取session對象,如果沒有則新建同時生成對應(yīng)的Cookie對象(JSESSIONID=xxx)返回給瀏覽器
- session對象對應(yīng)的Cookie對象(JSESSIONID=xxx): JSESSIONID是Cookie對象的name(唯一標識),根據(jù)name獲取對應(yīng)的Cookie對象然后獲取xxx查找對應(yīng)的session
- 用戶發(fā)起第二次請求, 瀏覽器自動將內(nèi)存中的Cookie對象封裝到請求協(xié)議中發(fā)送給服務(wù)器,服務(wù)器根據(jù)指定name的Cookie對象的value查找session對象(找不到則新建)
- 用戶關(guān)閉瀏覽器, 內(nèi)存消失(cookie消失和sessionid都會消失)
- 重新打開瀏覽器之后已經(jīng)沒有這個sessionid, 自然無法找到服務(wù)器端的session對象,等同于會話結(jié)束
- 服務(wù)器雖然不知道用戶關(guān)閉了瀏覽器, 但session的銷毀時機是依靠session超時機制決定或者點擊安全退出手動銷毀
// 張三第一次打開瀏覽器A訪問的服務(wù)器時候會在服務(wù)器端生成張三專屬的session對象
// 李四第一次打開瀏覽器B訪問服務(wù)器的時候同理生成李四專屬的session對象
// 下次獲取的時候張三再訪問的服務(wù)器的獲取的session對象就是張三的,李四再訪問服務(wù)器的時候獲取的session對象就是李四的
HttpSession session = request.getSession();
//銷毀session對象
session.invalidate()
獲取session及其存儲數(shù)據(jù)的方法
HttpServletRequest接口提供的getSession()方法可以用來從服務(wù)器端獲取當前的session對象,如果沒有獲取到則新建
- 當getSession()方法的參數(shù)是false時表示如果從服務(wù)器端沒有獲取到session對象并不會新建,而是返回一個null
方法名 | 功能 |
---|---|
void setAttribute(String name, Object obj) | 向會話域當中綁定數(shù)據(jù) |
Object getAttribute(String name) | 根據(jù)name從請求域當中獲取數(shù)據(jù) |
void removeAttribute(String name) | 將會話域當中綁定的數(shù)據(jù)移除 |
void invalidate() | 手動銷毀session對象 |
設(shè)置session的超時時長
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!--如果30分鐘過去了,session對象仍然沒有被訪問,session對象會被銷毀-->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
@WebServlet("/test/session")
public class TestSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 從WEB服務(wù)器當中獲取session對象,如果沒有則新建
HttpSession session = request.getSession();
// 獲取系統(tǒng)當前時間
Date nowTime = new Date();
// 向會話域當中綁定數(shù)據(jù)
session.setAttribute("sysTime",nowTime);
// 從會話域當中取數(shù)據(jù)
Object obj = session.getAttribute("sysTime")
// 將session對象響應(yīng)到瀏覽器
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("session域當中獲取的系統(tǒng)當前時間 = " + obj);
}
}
Cookie
概述
cookie怎么生成?cookie保存在什么地方?cookie有啥用?瀏覽器什么時候發(fā)送以及發(fā)送哪些cookie給服務(wù)器?
- 你每訪問一個網(wǎng)站服務(wù)器都會給你返回它對應(yīng)的Cookie對象(name=xxx…)
- 瀏覽器會將接收的Cookie對象(name=xxx…)保存在運行內(nèi)存中(瀏覽器只要關(guān)閉cookie就消失)或硬盤文件中(有效時間結(jié)束才會消失)
- cookie和session機制其實都是為了保存會話的狀態(tài): cookie是將會話的狀態(tài)保存在瀏覽器客戶端上, session是將會話的狀態(tài)保存在服務(wù)器端上
- 在HTTP協(xié)議中規(guī)定當瀏覽器發(fā)送請求的時候,會自動攜帶該請求路徑關(guān)聯(lián)的cookie對象給服務(wù)器
cookie機制和session機制不是java中的機制而是HTTP協(xié)議的一部分, 做web開發(fā)不管是什么編程語言cookie和session機制都是需要的
- HTTP協(xié)議中規(guī)定:任何一個cookie都是由字符串類型的name(Cookie對象的唯一標識)和value(Cookie對象中存儲的數(shù)據(jù))的鍵值對組成
- session對象對應(yīng)的Cookie對象(JSESSIONID=xxx): JSESSIONID是Cookie對象的name,根據(jù)name獲取對應(yīng)的Cookie對象然后獲取xxx查找對應(yīng)的session
Cookie禁用即服務(wù)器正常發(fā)送Cookie對象給瀏覽器但是瀏覽器不要了,這樣每一次瀏覽器發(fā)起請求都沒有攜帶sessionid, 服務(wù)器查找不到就會創(chuàng)建新的session對象
- 禁用了cookie需要使用URL重寫機制實現(xiàn)session機制: http://localhost:8080/servlet12/test/session;jsessionid=19D1C99560DCBF84839FA43D58F56E16
- URL重寫機制要求開發(fā)人員在編寫任何請求路徑的時候后面都要添加一個sessionid, 這給開發(fā)帶來了很大的難度, 所以大部分網(wǎng)站都不允許禁用cookie
cookie的經(jīng)典案例: 在未登錄的情況下向購物車中放幾件商品,關(guān)閉商城再次打開瀏覽器訪問的時候,購物車中的商品還在
- 將購物車中的商品編號放到Cookie對象(productIds=xxxxx,yyyy,)中并保存在硬盤文件,下次打開商城自動讀取本地硬盤中存儲的cookie然后動態(tài)展示商品
126郵箱中有一個功能:用戶輸入正確的用戶名和密碼,并且同時選擇十天內(nèi)免登錄
- 登錄成功后瀏覽器客戶端會保存一個cookie(保存了用戶名和密碼等信息),這個cookie保存在硬盤文件當中并且十天有效
- 在十天內(nèi)用戶再次訪問126的時候,瀏覽器自動提交126的關(guān)聯(lián)的cookie給服務(wù)器,服務(wù)器接收到cookie之后獲取用戶名和密碼驗證之后自動登錄成功
- 怎么讓cookie失效: 十天過后自動失效, 或者改密碼, 或者在客戶端瀏覽器上清除cookie(ctrl + shift + delete)
獲取和設(shè)置cookie參數(shù)的方法
servlet中對cookie提供的支持
-
HttpServletResponse接口提供的addCookie(cookie對象)方法可以把cookie數(shù)據(jù)發(fā)送給瀏覽器
-
HttpServletRequest接口提供的getCookies()可以獲取所有的Cookie,返回值是一個Cookie數(shù)組,注意沒有cookie的時候返回的是null
jakarta.servlet.http.Cookie提供的設(shè)置cookie相關(guān)參數(shù)的方法
方法名 | 功能 |
---|---|
Cookie (key,value) | 只有一個有參構(gòu)造方法用來創(chuàng)建Cookie對象 |
getName() | 獲取cookie的name |
getValue() | 獲取cookie的value |
setMaxAge(int) | 設(shè)置cookie的有效時間,以秒為單位, cookie.setMaxAge(60 * 60)表示設(shè)置cookie在一小時之后失效 |
setPath(“”) | 手動設(shè)置cookie關(guān)聯(lián)的路徑,瀏覽器上有很多cookie,瀏覽器發(fā)起不同的請求對應(yīng)路徑下關(guān)聯(lián)的cookie才會被提交到服務(wù)器 |
關(guān)于cookie的有效時間
- 沒有設(shè)置有效時間:默認保存在瀏覽器的運行內(nèi)存中,瀏覽器關(guān)閉則cookie消失
- 只要設(shè)置cookie的有效時間 > 0,這個cookie一定會存儲到硬盤文件當中
- 設(shè)置cookie的有效時間 = 0 : 刪除瀏覽器上的同名cookie
- 設(shè)置cookie的有效時間 < 0 : 保存在運行內(nèi)存中和不設(shè)置一樣
cookie關(guān)聯(lián)的路徑: 假設(shè)現(xiàn)在的cookie是由發(fā)送http://localhost:8080/servlet13/cookie/generate
請求路徑對應(yīng)的Servlet生成的
- cookie默認關(guān)聯(lián)的path, 當發(fā)送的請求路徑是
http://localhost:8080/servlet13/cookie
或它的子路徑時才會攜帶這個cookie提交到服務(wù)器 - 手動設(shè)置cookie關(guān)聯(lián)的path, cookie.setPath(“/servlet13”)表示只有是/servlet13或者它的子路徑才會提交這個cookie到服務(wù)器
瀏覽器發(fā)起請求,服務(wù)器生成cookie并響應(yīng)到瀏覽器
@WebServlet("/cookie/generate")
public class GenerateCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 創(chuàng)建Cookie對象
Cookie cookie = new Cookie("productid", "12345645623145612");
Cookie cookie2 = new Cookie("username", "zhangsan");
// 設(shè)置cookie的有效期 < 0,表示該cookie不會被存儲(表示不會被存儲到硬盤文件中,會放在瀏覽器運行內(nèi)存當中),和不調(diào)用sexMaxAge是同一個效果
cookie.setMaxAge(-1);
cookie2.setMaxAge(-1);
// 設(shè)置cookie的關(guān)聯(lián)路徑
cookie.setPath(request.getContextPath());
cookie2.setPath(request.getContextPath());
// 將多個cookie響應(yīng)到瀏覽器
response.addCookie(cookie);
response.addCookie(cookie2);
}
}
瀏覽器發(fā)送cookie給服務(wù)器了,通過java程序接收瀏覽器發(fā)送過來的cookie
@WebServlet("/sendCookie")
public class ReceiveCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 如果瀏覽器沒有提交cookie,這個方法返回值是null,并不是返回一個長度為0的數(shù)組
Cookie[] cookies = request.getCookies();
// 如果不是null,表示一定有cookie
if (cookies != null) {
// 遍歷數(shù)組
for (Cookie cookie : cookies) {
// 獲取cookie的name和value
String name = cookie.getName();
String value = cookie.getValue();
System.out.println(name + "=" + value);
}
}
}
}
完善單表的(免)登錄退出功能
實現(xiàn)登錄功能
步驟1:數(shù)據(jù)庫當中添加一個用戶表t_user并向表中插入一條用戶數(shù)據(jù)
- t_user表當中存儲的是用戶基本的登錄信息: 登錄的用戶名和登錄的密碼
- 密碼一般在數(shù)據(jù)庫表當中存儲的是密文(MD加密算法) ,一般不以明文的形式存儲(這里先使用明文方式)
步驟2:實現(xiàn)一個登錄頁面的表單(包含用戶名和密碼輸入框) , 用戶點擊登錄時利用表單發(fā)起post請求提交用戶名和密碼
- request.getContextPath()可以動態(tài)的獲取一個應(yīng)用的根路徑
步驟3:后臺編寫一個對應(yīng)的Servlet處理登錄的請求
- 登錄成功:跳轉(zhuǎn)到部門列表頁面(登錄成功必須獲取到session對象,沒有session也要新建一個session對象)
- 登錄失?。禾D(zhuǎn)到提供的登錄失敗的頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登錄失敗</title>
</head>
<body>
登錄失敗,請<a href="${pageContext.request.contextPath}/index.jsp">重新登錄</a>
</body>
</html>
使用session機制解決用戶在不登錄的情況下直接通過后端的請求路徑訪問系統(tǒng)的問題
- 可以在登錄成功之后獲取session對象存儲用戶的登錄信息(第一次登錄肯定獲取不到所以需要新建)
@WebServlet({"/user/login","/user/exit"})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
if("/user/login".equals(servletPath)){
doLogin(request, response);
}else if("/user/exit".equals(servletPath)){
doExit(request, response);
}
}
protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean success = false;
// 獲取用戶名和密碼驗證是否正確,前端提交格式:username=admin&password=123
String username = request.getParameter("username");
String password = request.getParameter("password");
// 連接數(shù)據(jù)庫驗證用戶名和密碼
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user where username = ? and password = ?";
// 編譯SQL
ps = conn.prepareStatement(sql);
// 給?傳值
ps.setString(1, username);
ps.setString(2, password);
// 執(zhí)行SQL
rs = ps.executeQuery();
// 這個結(jié)果集當中最多只有一條數(shù)據(jù)
if (rs.next()) { // 不需要while循環(huán)
// 登錄成功
success = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, rs);
}
// 登錄成功/失敗
if (success) {
// 登錄成功必須獲取到session對象,沒有session也要新建一個session對象
HttpSession session = request.getSession();
// 把用戶信息存到會話域中
session.setAttribute("username", username);
// 成功跳轉(zhuǎn)到用戶列表頁面
response.sendRedirect(request.getContextPath() + "/dept/list");
} else {
// 失敗跳轉(zhuǎn)到失敗頁面
response.sendRedirect(request.getContextPath() + "/error.jsp");
}
}
}
當用戶通過訪問路徑的方式訪問系統(tǒng)時需要先獲取當前的session對象
- 獲取不到返回null不能新建session,session為null說明用戶沒有登錄需要先登錄
- 獲取到后判斷session對象是否存儲的有用戶的信息
@WebServlet({"/dept/list", "/dept/detail", "/dept/delete", "/dept/save", "/dept/modify"})
public class DeptServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取當前session對象獲取不到返回null
// 如果直接訪問jsp頁面可以拿到是jsp內(nèi)置的session對象
HttpSession session = request.getSession(false);
// 獲取到session對象并且session中有數(shù)據(jù)表示用戶登錄過
if(session != null && session.getAttribute("username") != null){
String servletPath = request.getServletPath();
if("/dept/list".equals(servletPath)){
doList(request, response);
}else if("/dept/detail".equals(servletPath)){
doDetail(request, response);
}else if("/dept/delete".equals(servletPath)){
doDel(request, response);
}else if("/dept/save".equals(servletPath)){
doSave(request, response);
}else if("/dept/modify".equals(servletPath)){
doModify(request, response);
}
}else{
// 跳轉(zhuǎn)到登錄頁面,訪問web站點的根即可,自動找到歡迎頁面
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
cookie實現(xiàn)十天內(nèi)免登錄功能
在登錄頁面給一個復(fù)選框,復(fù)選框后面給一句話十天內(nèi)免登錄
- 用戶選擇了復(fù)選框表示用戶想要十天內(nèi)免登錄 , 沒有選擇復(fù)選框表示用戶不想使用十天內(nèi)免登錄功能
<%@page contentType="text/html;charset=UTF-8"%>
<%--訪問jsp的時候不生成session對象。--%>
<%@page session="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>歡迎使用OA系統(tǒng)</title>
</head>
<body>
<h1>LOGIN PAGE</h1>
<hr>
<%--前端頁面發(fā)送請求的時候,請求路徑以“/”開始,帶項目名。--%>
<form action="${pageContext.request.contextPath}/user/login" method="post">
username: <input type="text" name="username" ><br>
password: <input type="password" name="password"><br>
<input type="checkbox" name="f" value="1">十天內(nèi)免登錄<br>
<input type="submit" value="login">
</form>
</body>
</html>
如果用戶登錄成功了,并且用戶登錄時也選擇了十天內(nèi)免登錄功能
- 在Servlet的login方法中創(chuàng)建cookie用來存儲用戶名和密碼,設(shè)置關(guān)聯(lián)路徑(項目根目錄)和有效期(十天),最后將cookie響應(yīng)給瀏覽器
- 瀏覽器下次發(fā)送這個cookie關(guān)聯(lián)的請求路徑時就會攜帶這個cookie供服務(wù)器進行驗證
@WebServlet({"/user/login","/user/exit"})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String servletPath = request.getServletPath();
if("/user/login".equals(servletPath)){
doLogin(request, response);
}else if("/user/exit".equals(servletPath)){
doExit(request, response);
}
}
// 十天內(nèi)免登錄
protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean success = false;
// 獲取用戶名和密碼,驗證是否正確
// 前端你是這樣提交的:username=admin&password=123
String username = request.getParameter("username");
String password = request.getParameter("password");
// 連接數(shù)據(jù)庫驗證用戶名和密碼
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user where username = ? and password = ?";
// 編譯SQL
ps = conn.prepareStatement(sql);
// 給?傳值
ps.setString(1, username);
ps.setString(2, password);
// 執(zhí)行SQL
rs = ps.executeQuery();
// 這個結(jié)果集當中最多只有一條數(shù)據(jù)。
if (rs.next()) { // 不需要while循環(huán)
// 登錄成功
success = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, rs);
}
// 登錄成功/失敗
if (success) {
// 登錄成功必須獲取到session對象,沒有session也要新建一個session對象
HttpSession session = request.getSession();
//把用戶信息存到會話域中
session.setAttribute("username", username);
User user = new User(username, password);
session.setAttribute("user", user);
// 登錄成功了,并且用戶確實選擇了“十天內(nèi)免登錄”功能
String f = request.getParameter("f");
if("1".equals(f)){
// 創(chuàng)建Cookie對象存儲登錄名
Cookie cookie1 = new Cookie("username", username);
// 創(chuàng)建Cookie對象存儲密碼,密碼一般不直接存儲,真實情況下是加密的
Cookie cookie2 = new Cookie("password", password);
// 設(shè)置cookie的有效期為十天
cookie1.setMaxAge(60 * 60 * 24 * 10);
cookie2.setMaxAge(60 * 60 * 24 * 10);
// 設(shè)置cookie的path(只要訪問這個應(yīng)用,瀏覽器就一定要攜帶這兩個cookie)
cookie1.setPath(request.getContextPath());
cookie2.setPath(request.getContextPath());
// 響應(yīng)cookie給瀏覽器
response.addCookie(cookie1);
response.addCookie(cookie2);
}
// 成功,跳轉(zhuǎn)到用戶列表頁面
response.sendRedirect(request.getContextPath() + "/dept/list");
} else {
// 失敗,跳轉(zhuǎn)到失敗頁面
response.sendRedirect(request.getContextPath() + "/error.jsp");
}
}
用戶重新打開瀏覽器再次訪問該網(wǎng)站的時候有兩個走向, 要么跳轉(zhuǎn)到部門列表頁面或跳轉(zhuǎn)到登錄頁面 , 這兩個走向需要編寫java程序進行控制的文章來源:http://www.zghlxwxcb.cn/news/detail-600702.html
- 獲取瀏覽器中所有的cookie進行遍歷,如果存在兩個cookie的用戶名和密碼都正確則直接跳轉(zhuǎn)到部門列表頁面, 否則跳轉(zhuǎn)到登錄頁面
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!--手動配置默認歡迎頁面,默認從應(yīng)用的根下開始不用加/,當訪問根目錄時默認發(fā)起/oa/welcome請求-->
<welcome-file-list>
<welcome-file>welcome</welcome-file>
</welcome-file-list>
</web-app>
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 這個Cookie[]數(shù)組可能是null,如果不是null數(shù)組的長度一定是大于0的
Cookie[] cookies = request.getCookies();
String username = null;
String password = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
if("username".equals(name)){
username = cookie.getValue();
}else if("password".equals(name)){
password = cookie.getValue();
}
}
}
// 使用username和password變量驗證用戶名和密碼是否正確
if(username != null && password != null){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean success = false;
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user where username = ? and password = ?";
ps = conn.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2,password);
rs = ps.executeQuery();
if (rs.next()) {
// 登錄成功
success = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, rs);
}
if (success) {
// 獲取session
HttpSession session = request.getSession();
session.setAttribute("username", username);
User user = new User(username, password);
session.setAttribute("user", user);
// 正確,表示登錄成功
response.sendRedirect(request.getContextPath() + "/dept/list");
}else{
// 錯誤,表示登錄失敗, 跳轉(zhuǎn)到登錄頁面
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}else{
// 跳轉(zhuǎn)到登錄頁面
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
}
安全退出功能
安全退出的按鈕在list.jsp動態(tài)響應(yīng)的內(nèi)容中: 退出后用戶不能直接訪問用戶列表頁面文章來源地址http://www.zghlxwxcb.cn/news/detail-600702.html
<h3>歡迎${username},在線人數(shù)${onlinecount}人</h3>
<a href="user/exit">[退出系統(tǒng)]</a>
protected void doExit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取并銷毀session,這個session可能為null
HttpSession session = request.getSession(false);
if (session != null) {
// 手動銷毀session對象
session.invalidate();
// 銷毀cookie(退出系統(tǒng)將所有的cookie全部銷毀)
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
// 設(shè)置cookie的有效期為0,表示刪除該cookie
cookie.setMaxAge(0);
// 設(shè)置cookie的關(guān)聯(lián)路徑
cookie.setPath(request.getContextPath()); // 刪除cookie的時候注意路徑問題
// 響應(yīng)cookie給瀏覽器,瀏覽器端會將之前的cookie覆蓋
response.addCookie(cookie);
}
}
// 跳轉(zhuǎn)到登錄頁面
response.sendRedirect(request.getContextPath());
}
}
到了這里,關(guān)于(13)session和cookie的原理分析,完成(免)登錄和安全退出功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!