會話
會話:指的是一個客戶端(瀏覽器)與Web服務器之間連續發生的一系列請求和響應的過程。
客戶端和服務器的請求和響應的過程(對話雙方只要有一方發生變化,都屬于不同的會話)
超時間隔【距離上一次請求的間隔】,超時后就屬于不同的會話
HTTP是無狀態的,不保存用戶信息
Cookie客戶端
Session服務器
Cookie
Cookie是一種會話技術,它用于將會話過程中的數據保存到用戶的瀏覽器中【保存在客戶端的磁盤或緩存(內存)中】,從而使瀏覽器和服務器可以更好地進行數據交互。
用戶第一次訪問時,沒有Cookie
Cookie API
Cookie的相關方法
Cookie–setMaxAge()和getMaxAge()
負數:瀏覽器一關,緩存就會清空【將Cookie保存在瀏覽器的緩存中】
默認為-1
Cookie的案例
/*** Illustration** @author dengqing* @time 2021/10/13* @function cookie上次訪問時間*/@WebServlet(name = "Cookie1", value = "/cookie1")
public class Cookie1 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html; charset=UTF-8");//字符輸出流PrintWriter out = response.getWriter();Date date = new Date();//格式化輸出SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");//獲取當前時間String NowTime = sdf.format(date);//創建Cookie對象并保存當前時間到Cookie對象之中Cookie cookie = new Cookie("LastTime", NowTime);//將Cookie信息回寫至客戶端瀏覽器response.addCookie(cookie);//設置cookie保存在磁盤中,為90秒;90秒后失效cookie.setMaxAge(90);//把瀏覽器中所有Cookie返回//Cookie[] cookies:Cookie對象數組Cookie[] cookies = request.getCookies();String LastAccessTime = null;//如果cookies不為空,再循環,防止空指針異常if (cookies != null) {//增強型for循環for (Cookie c : cookies) {//匹配是否有"LastTime" Cookie//"LastTime"字符串寫在前面,防止空指針異常if ("LastTime".equals(c.getName())) {//獲取Cookie的值,如果為空,則為瀏覽器第一次訪問LastAccessTime = c.getValue();}}}//Cookie的值,如果為空,則為瀏覽器第一次訪問if (LastAccessTime.isEmpty()) {out.write("你是首次訪問本站!");} else {//每次刷新,就會重新計算90秒:cookie.setMaxAge(90);//90秒后失效,就又會顯示:你是首次訪問本站!out.write("你上次訪問本站的時間:" + LastAccessTime);}}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
Session會話
Cookie是鍵值對,不能存儲大量數據【每次放在請求頭中】,并且不安全,效率低
所以使用Session存儲大量數據,Session是一種將會話數據保存到服務器端的技術
說會話,指Session
Session的創建,由Servlet容器在發起會話時自動創建
當瀏覽器訪問Web服務器時,Servlet容器就會創建一個Session對象和ID屬性【32位16進制,16的32次方,2^128次方,ID不會重復,類似IPv6,64位】,當客戶端后續訪問服務器時,只要將標識號傳遞給服務器,服務器就能判斷出該請求是哪個客戶端發送的,從而選擇與之對應的Session對象為其服務。
由于客戶端需要接收、記錄和回送Session對象的ID,因此,通常情況下,Session是借助Cookie技術來傳遞ID屬性的。
Session原理
Session是通過Cookie技術實現的,依賴于名為JSESSIONID的Cookie,它將信息保存在服務器端。Session中能夠存儲復雜的Java對象,因此使用更加方便。如果客戶端不支持Cookie,或者禁用了Cookie,仍然可以通過使用URL重寫來使用Session。
Session-獲取Session對象
不同的請求對象獲取的Session對象,不一定不同;因為可能是處于同一次會話
同一個瀏覽器的不同窗口是同一個Session;不同的瀏覽器是不同Session
Session相關方法
大型項目一般使用時間戳,國內外一致【getLastAccessedTime()】
Sesssion超時,設置為分鐘,在超時時間內如果沒有任何請求則超時
invalidate():類似刪除Session
Tomcat的Session超時設置
Session案例
瀏覽器不同窗口屬于同一次會話
瀏覽器關閉,則結束會話了
loginServlet.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<!--等效-->
<!--action="http://localhost:8082/WebServletProject_war_exploded/loginServlet"-->
<form action="loginServlet"><!--div標簽:把組件分割開--><!--placeholder 是HTML5 中新增的一個屬性。placeholder可以用來描述輸入字段預期值的簡短的提示信息。提示信息會在用戶輸入值之前顯示,一旦用戶輸入信息該提示就會自動消失。--><!--placeholder :提示用戶輸入信息--><div><input type="text" name="uname" placeholder="用戶名"></div><input type="password" name="upwd" placeholder="密碼"></br><div><input type="submit" value="登錄"></div></form>
</body>
</html>
LoginServlet.java
/*** Illustration** @author dengqing* @time 2021/10/13* @function Session:實現登錄成功后存入Session;獲取Sesssion數據*///http://localhost:8082/WebServletProject_war_exploded/loginServlet.html
@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();System.out.println("進入loginServlet登錄頁面...");//獲取login.html頁面用戶輸入的值String name = request.getParameter("uname");String pwd = request.getParameter("upwd");if ("admin".equals(name) && "123".equals(pwd)) {//獲取對話SessionHttpSession session = request.getSession();//將當前用戶的名稱存入Sessionsession.setAttribute("user",name);//<script>alert('登錄成功')</script>:JavaScript,彈出警告框out.write("<script>alert('登錄成功')</script>");response.sendRedirect("mainServlet");} else {out.write("用戶名或密碼輸入錯誤");response.sendRedirect("loginServlet.html");}}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
MainServlet.java
@WebServlet(name = "MainServlet", value = "/mainServlet")
public class MainServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();//獲取當前對話的Session對象HttpSession session = request.getSession();//獲取Session的用戶名稱Object user = session.getAttribute("user");//不為空,之前已經登錄過,直接訪問if (user!=null){out.write("進入MainServelt主頁面");out.write("歡迎回來!"+(String)user);}else {out.write("你還沒有登錄,請先登錄后再訪問此頁面!\n");out.write("<a href='loginServlet.html'>點擊此處進行登錄!</a>");}}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
Java Bean
JavaBean符合一定規范寫的Java類,是一種規范。它的方法命名,構造以及行為必須符合特定的要求:
1.所有屬性為private
2.這個類必須具有一個公共的(public)無參構造函數
3.private屬性必須提供public的getter和setter來給外部訪問,并且方法的命名也必須遵循一定的命名規范
4.這個類是可序列化的,要實現serializable接口
JavaBean,類必須是具體的和公共的,并且具有無參數的構造器。JavaBean 通過提供符合一致性設計模式的公共方法將內部域暴露成員屬性。眾所周知,屬性名稱符合這種模式,其他Java 類可以通過自身機制發現和操作這些JavaBean 的屬性。