1. 概念:服務器端會話技術,在一次會話的屢次請求間共享數據,將數據保存在服務器端的對象中。HttpSession 2. 快速入門: 1. 獲取HttpSession對象: HttpSession session = request.getSession(); 2. 使用HttpSession對象: Object getAttribute(String name) void setAttribute(String name, Object value) void removeAttribute(String name)
package cn.itcast.session;html
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;java
@WebServlet("/sessionDemo1")
public class SessionDemo1 extends HttpServlet {web
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //使用session共享數據 //1.獲取session HttpSession session = request.getSession(); //2.存儲數據 session.setAttribute("msg","hello session"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
}
package cn.itcast.session;數據庫
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;瀏覽器
@WebServlet("/sessionDemo2")
public class SessionDemo2 extends HttpServlet {tomcat
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //使用session獲取數據 //1.獲取session HttpSession session = request.getSession(); //2.獲取數據 Object msg = session.getAttribute("msg"); System.out.println(msg); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
}安全
* 默認狀況下。不是。 * 若是須要相同,則能夠建立Cookie,鍵爲JSESSIONID,設置最大存活時間,讓cookie持久化保存。 Cookie c = new Cookie("JSESSIONID",session.getId()); c.setMaxAge(60*60); response.addCookie(c);
package cn.itcast.session;服務器
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;cookie
@WebServlet("/sessionDemo3")
public class SessionDemo3 extends HttpServlet {session
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.獲取session HttpSession session = request.getSession(); System.out.println(session); //以上關閉瀏覽器後再執行打印的session不是同一個,可是設置了下邊的代碼之後打印的session是同一個了 //指望客戶端關閉後,session也能相同 Cookie c = new Cookie("JSESSIONID",session.getId()); c.setMaxAge(60*60); response.addCookie(c); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
}
package cn.itcast.session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/sessionDemo4")
public class SessionDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.獲取session HttpSession session = request.getSession(); System.out.println(session); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
}
* 不是同一個,可是要確保數據不丟失。tomcat自動完成如下工做 * session的鈍化: * 在服務器正常關閉以前,將session對象系列化到硬盤上 * session的活化: * 在服務器啓動後,將session文件轉化爲內存中的session對象便可。
將out工做目錄下的項目打包成war文件夾
把war文件夾放到tomcat的webapp目錄
關掉idea本地的tomcat
啓動tomcat
訪問locahost:8080/day16/sessionDemo1
而後訪問localhost:8080/day16/sessionDemo2
正常關閉服務器
從新啓動後session的序列化文件刪除 內容從新還原到內存中了
那麼在idea的Catalina_base的目錄是相似於
C:UsersAdministrator.IntelliJIdea2019.2systemtomcat_learn
在idea重啓tomcat的目錄的時候會把work目錄刪掉
等一會會建立一個work文件,可是文件中沒有對應的session文件了
1. 服務器關閉 2. session對象調用invalidate() 。 3. session默認失效時間 30分鐘 選擇性配置修改 <session-config> <session-timeout>30</session-timeout> </session-config>
1. session用於存儲一次會話的屢次請求的數據,存在服務器端 2. session能夠存儲任意類型,任意大小的數據 * session與Cookie的區別: 1. session存儲數據在服務器端,Cookie在客戶端 2. session沒有數據大小限制,Cookie有 3. session數據安全,Cookie相對於不安全
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title> <script> window.onload = function(){ document.getElementById("img").onclick = function(){ this.src="/day16/checkCodeServlet?time="+new Date().getTime(); } } </script> <style> div{ color: red; } </style>
</head>
<body>
<form action="/day16/loginServlet" method="post"> <table> <tr> <td>用戶名</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="password"></td> </tr> <tr> <td>驗證碼</td> <td><input type="text" name="checkCode"></td> </tr> <tr> <td colspan="2"><img id="img" src="/day16/checkCodeServlet"></td> </tr> <tr> <td colspan="2"><input type="submit" value="登陸"></td> </tr> </table> </form> <div><%=request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error")%></div> <div><%=request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error") %></div>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1><%=request.getSession().getAttribute("user")%>,歡迎您</h1>
</body>
</html>
package cn.itcast.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.設置request編碼 request.setCharacterEncoding("utf-8"); //2.獲取參數 String username = request.getParameter("username"); String password = request.getParameter("password"); String checkCode = request.getParameter("checkCode"); //3.先獲取生成的驗證碼 HttpSession session = request.getSession(); String checkCode_session = (String) session.getAttribute("checkCode_session"); //刪除session中存儲的驗證碼 session.removeAttribute("checkCode_session"); //3.先判斷驗證碼是否正確 if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(checkCode)){ //忽略大小寫比較 //驗證碼正確 //判斷用戶名和密碼是否一致 if("zhangsan".equals(username) && "123".equals(password)){//須要調用UserDao查詢數據庫 //登陸成功 //存儲信息,用戶信息 session.setAttribute("user",username); //重定向到success.jsp response.sendRedirect(request.getContextPath()+"/success.jsp"); }else{ //登陸失敗 //存儲提示信息到request request.setAttribute("login_error","用戶名或密碼錯誤"); //轉發到登陸頁面 request.getRequestDispatcher("/login.jsp").forward(request,response); } }else{ //驗證碼不一致 //存儲提示信息到request request.setAttribute("cc_error","驗證碼錯誤"); //轉發到登陸頁面 request.getRequestDispatcher("/login.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
}
package cn.itcast.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 100; int height = 50; //1.建立一對象,在內存中圖片(驗證碼圖片對象) BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //2.美化圖片 //2.1 填充背景色 Graphics g = image.getGraphics();//畫筆對象 g.setColor(Color.PINK);//設置畫筆顏色 g.fillRect(0,0,width,height); //2.2畫邊框 g.setColor(Color.BLUE); g.drawRect(0,0,width - 1,height - 1); String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789"; //生成隨機角標 Random ran = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 4; i++) { int index = ran.nextInt(str.length()); //獲取字符 char ch = str.charAt(index);//隨機字符 sb.append(ch); //2.3寫驗證碼 g.drawString(ch+"",width/5*i,height/2); } String checkCode_session = sb.toString(); //將驗證碼存入session request.getSession().setAttribute("checkCode_session",checkCode_session); //2.4畫干擾線 g.setColor(Color.GREEN); //隨機生成座標點 for (int i = 0; i < 10; i++) { int x1 = ran.nextInt(width); int x2 = ran.nextInt(width); int y1 = ran.nextInt(height); int y2 = ran.nextInt(height); g.drawLine(x1,y1,x2,y2); } //3.將圖片輸出到頁面展現 ImageIO.write(image,"jpg",response.getOutputStream()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); }
}