會話技術:
會話:瀏覽器訪問服務器端,發送多次請求,接受多次響應。直到有一方斷開連接。會話結束。
解決問題:可以使用會話技術,在一次會話的多次請求之間共享數據。
分類:
客戶端會話技術 Cookie
服務器端會話技術 Session
客戶端會話技術:Cookie 小餅干的意思
服務器端不需要管理,方便。但是不安全。
原理:
1.客戶端第一次請求服務器端,服務器作出響應時,會發送set-cookie頭,攜帶需要共享的數據
2.當客戶端接受到這個響應,會將數據存儲在客戶端
3.當客戶端再次請求服務器端時,會通過cookie請求頭攜帶着存儲的數據。
4.服務器接受帶請求,會獲取客戶端攜帶的數據。
Java代碼實現:
1.發送cookie
//1.創建Cookie對象。
Cookie c = new Cookie("name","zhangsan");
//2.通過response發送cookie
response.addCookie(c);
2.接收cookie
//1.獲取所有cookie數組
Cookie[] cs = request.getCookies();
//2.遍歷數組
if(cs != null){
for (Cookie c : cs) {
//獲取cookie的名稱
String name = c.getName();
//判斷名稱,得到目標cookie
if("name".equals(name)){
//獲取值
String value = c.getValue();
System.out.println(name+":"+value);
}
}
}
Cookie的細節:
1.默認情況下,cookie保存在客戶端瀏覽器內存中。
需要將數據持久化存儲在客戶端的硬盤上。
設置cookie的存活時間。setMaxAge(int s);
2.Cookie是不支持中文數據的。如果要想存儲中文數據。需要轉碼。
URL編碼
功能:記住用戶名和密碼
服務器端會話技術:Session 主菜的意思
服務器端需要管理數據,麻煩,但是安全。
原理:
1.客戶端訪問服務器端,在服務器端的一個對象(Session)中存儲了數據
2.服務器給客戶端作出響應時,會自動將session對象的id通過響應頭 set-cookie:jsessionid=xxx 發送到客戶端
3.客戶端接受到響應,將頭對應的值存儲到客戶端
4.客戶端再次請求時,會攜帶着請求頭 cookie:jsessionid=xxx.
5.服務器接受到請求,通過jsessionid的值,找到對應的session對象。就可以獲取對象中存儲的數據了。
Session技術依賴於cookie。
獲取session
HttpSession session = request.getSession();
域對象:
setAttribute():
getAttribute():
removeAttribute():
session細節:
1.客戶端關閉了,兩次session一樣嗎?
不一樣。因為客戶端瀏覽器內存釋放了,jsessionid沒了。
服務器關閉了,兩次session一樣嗎?
不一樣。因為服務器內存釋放了,session對象沒了。
session的鈍化:
當服務器正常關閉時,會將session對象寫入到服務器的硬盤上。
session的活化:
當服務器正常啟動時,會將session文件還原為session對象
2.session對象的銷毀
1.session超時
<session-config>
<session-timeout>30</session-timeout>
</session-config>
2.invalidate():session銷毀
3.服務器關閉。
3.session依賴於cookie,如果客戶端禁用了cookie,那么session該咋辦?
URL重寫。
4.getSession方法的重載:
boolean:
true:默認值
通過id查找session,如果沒找到,新創建一個
false:
通過id查找session,如果沒找到,返回null
第一次創建一個新的對象
代碼演示:
1 package cookie; 2 3 import java.io.IOException; 4 import java.sql.PreparedStatement; 5 import java.sql.SQLException; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import javax.servlet.http.HttpSession; 12 13 public class LoginServlet extends HttpServlet { 14 15 private static final long serialVersionUID = -4372317815130787297L; 16 17 public void doGet(HttpServletRequest request, HttpServletResponse response) 18 throws ServletException, IOException { 19 try { 20 //1.獲取驗證碼 21 String checkCode = request.getParameter("checkCode"); 22 //2.獲取生成的驗證碼 23 HttpSession session = request.getSession(); 24 String checkCode_pro = (String) session.getAttribute("checkCode_pro"); 25 26 //1.設置編碼 27 request.setCharacterEncoding("utf-8"); 28 //2.獲取用戶名和密碼 29 String username = request.getParameter("username"); 30 String password = request.getParameter("password"); 31 //3.操作數據庫,獲取數據庫連接 32 //4.定義sql 33 //5.獲取pstmt對象 34 PreparedStatement pstmt = JDBCUtils.getConnection().prepareStatement("select * from user where username = ? and userpassword = ?"); 35 //6.設置參數 36 pstmt.setString(1, username); 37 pstmt.setString(2, password); 38 //7.執行sql 39 //8.驗證,判斷 40 //判斷驗證碼是否正確 41 if(checkCode_pro.equalsIgnoreCase(checkCode)){ 42 //正確 43 //注冊 或 登錄 44 session.setAttribute("regist_msg", "驗證碼正確"); 45 if(pstmt.executeQuery().next()){ 46 //登陸成功 47 request.setAttribute("username", username); 48 request.getRequestDispatcher("/success.jsp").forward(request, response); 49 }else{ 50 //登陸失敗 51 request.setAttribute("msg", "用戶名或密碼錯誤!"); 52 request.getRequestDispatcher("/login.jsp").forward(request, response); 53 } 54 }else{ 55 //錯誤 56 session.setAttribute("regist_msg", "驗證碼錯誤"); 57 response.sendRedirect("/colloquy/login.jsp"); 58 //將session中存儲的驗證碼清空 59 session.removeAttribute("checkCode_pro"); 60 } 61 } catch (SQLException e) { 62 e.printStackTrace(); 63 } 64 } 65 66 public void doPost(HttpServletRequest request, HttpServletResponse response) 67 throws ServletException, IOException { 68 this.doGet(request, response); 69 } 70 }
1 package cookie; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.Cookie; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class RemServlet extends HttpServlet { 12 13 private static final long serialVersionUID = -3477344209817695234L; 14 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 //1.獲取用戶名和密碼,復選框 18 String username = request.getParameter("username"); 19 String password = request.getParameter("password"); 20 //2.判斷用戶名和密碼是否正確 21 if("zhangsan".equals(username) && "123".equals(password)){ 22 //登陸成功 23 if(request.getParameter("rem") != null){ 24 //記住密碼 25 //1.創建cookie 26 Cookie c_username = new Cookie("username", username); 27 Cookie c_password = new Cookie("password", password); 28 //2.設置存活時間 29 c_username.setMaxAge(60 * 60 * 24 * 7); 30 c_password.setMaxAge(60 * 60 * 24 * 7); 31 //3.發送cookie 32 response.addCookie(c_username); 33 response.addCookie(c_password); 34 } 35 request.setAttribute("username", username); 36 request.getRequestDispatcher("/success.jsp").forward(request, response); 37 }else{ 38 //登陸失敗 39 request.setAttribute("msg", "用戶名或密碼錯誤!"); 40 request.getRequestDispatcher("/login.jsp").forward(request, response); 41 } 42 } 43 44 public void doPost(HttpServletRequest request, HttpServletResponse response) 45 throws ServletException, IOException { 46 this.doGet(request, response); 47 } 48 }
1 package cookie; 2 3 import java.awt.Color; 4 import java.awt.Graphics; 5 import java.awt.image.BufferedImage; 6 import java.io.IOException; 7 import java.util.Random; 8 9 import javax.imageio.ImageIO; 10 import javax.servlet.ServletException; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 15 /** 16 * 生成驗證碼 17 * @author rongsnow 18 * 19 */ 20 public class CheckCodeServlet extends HttpServlet { 21 22 private static final long serialVersionUID = 8583894656985684165L; 23 24 public void doGet(HttpServletRequest request, HttpServletResponse response) 25 throws ServletException, IOException { 26 27 int width = 100; 28 int height = 50; 29 //1.創建圖片 30 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 31 //2.裝飾圖片 32 //2.1設置背景色 33 //2.1.1 獲取畫筆對象 34 Graphics g = image.getGraphics(); 35 //2.2.2 設置畫筆的顏色 36 g.setColor(Color.pink); 37 //2.2.3 填充背景色 38 g.fillRect(0, 0, width, height); 39 40 //2.2 畫邊框 41 g.setColor(Color.GREEN); 42 g.drawRect(0, 0, width - 1, height - 1); 43 44 //2.3 寫入驗證碼 45 g.setColor(Color.RED); 46 47 String msg = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 48 Random ran = new Random(); 49 StringBuilder sb = new StringBuilder(); 50 for (int i = 1; i <= 4; i++) { 51 int index = ran.nextInt(msg.length());//隨機生成角標 52 String s = String.valueOf(msg.charAt(index)); 53 sb.append(s); 54 55 g.drawString(s, width/5 * i, height/2); 56 } 57 String checkCode_pro = sb.toString(); 58 //將生成的驗證碼 存入session 59 request.getSession().setAttribute("checkCode_pro", checkCode_pro); 60 61 //2.4畫干擾線 62 g.setColor(Color.BLUE); 63 64 for (int i = 0; i < 5; i++) { 65 //動態生成坐標點 66 int x1 = ran.nextInt(width); 67 int x2 = ran.nextInt(width); 68 int y1 = ran.nextInt(height); 69 int y2 = ran.nextInt(height); 70 g.drawLine(x1, y1, x2, y2); 71 } 72 73 //3.將圖片數據 寫入到 response輸出流中 74 ImageIO.write(image, "jpg", response.getOutputStream()); 75 } 76 77 public void doPost(HttpServletRequest request, HttpServletResponse response) 78 throws ServletException, IOException { 79 80 this.doGet(request, response); 81 } 82 }
1 package cookie; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 import java.io.IOException; 6 import java.sql.Connection; 7 import java.sql.DriverManager; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 import java.sql.Statement; 11 import java.util.Properties; 12 13 /** 14 * JDBC 工具類 15 * @author rongsnow 16 * 17 */ 18 public class JDBCUtils { 19 private static String url = null; 20 private static String user = null; 21 private static String password = null; 22 private static String driverClass = null; 23 24 static{ 25 /* 26 * 加載配置文件,為每一個值賦值 27 */ 28 try { 29 //1.創建properties對象 30 Properties pro = new Properties(); 31 //獲取配置文件的真實路徑 32 //2.關聯資源文件 33 pro.load(new FileReader(JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath())); 34 //3.獲取數據 35 url = pro.getProperty("url"); 36 user = pro.getProperty("user"); 37 password = pro.getProperty("password"); 38 driverClass = pro.getProperty("driverClass"); 39 //4.注冊驅動 40 Class.forName(driverClass); 41 42 } catch (FileNotFoundException e) { 43 e.printStackTrace(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } catch (ClassNotFoundException e) { 47 e.printStackTrace(); 48 } 49 } 50 51 /** 52 * 獲取數據庫連接 53 * @throws SQLException 54 */ 55 public static Connection getConnection() throws SQLException{ 56 57 return DriverManager.getConnection(url, user, password); 58 } 59 60 /** 61 * 釋放資源 62 * @throws SQLException 63 */ 64 public static void close(Connection conn,Statement stmt,ResultSet rs) throws SQLException{ 65 if(rs != null){//預防空指針異常 66 rs.close(); 67 } 68 if(stmt != null){//預防空指針異常 69 stmt.close(); 70 } 71 if(conn != null){//預防空指針異常 72 conn.close(); 73 } 74 } 75 public static void close(Connection conn,Statement stmt) throws SQLException{ 76 if(stmt != null){//預防空指針異常 77 stmt.close(); 78 } 79 if(conn != null){//預防空指針異常 80 conn.close(); 81 } 82 } 83 public static void close(Connection conn) throws SQLException{ 84 if(conn != null){//預防空指針異常 85 conn.close(); 86 } 87 } 88 }
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <display-name></display-name> 8 9 <servlet> 10 <description>This is the description of my J2EE component</description> 11 <display-name>This is the display name of my J2EE component</display-name> 12 <servlet-name>LoginServlet</servlet-name> 13 <servlet-class>cookie.LoginServlet</servlet-class> 14 </servlet> 15 <servlet> 16 <description>This is the description of my J2EE component</description> 17 <display-name>This is the display name of my J2EE component</display-name> 18 <servlet-name>RemServlet</servlet-name> 19 <servlet-class>cookie.RemServlet</servlet-class> 20 </servlet> 21 <servlet> 22 <description>This is the description of my J2EE component</description> 23 <display-name>This is the display name of my J2EE component</display-name> 24 <servlet-name>checkcode</servlet-name> 25 <servlet-class>cookie.CheckCodeServlet</servlet-class> 26 </servlet> 27 28 29 <servlet-mapping> 30 <servlet-name>LoginServlet</servlet-name> 31 <url-pattern>/loginServlet</url-pattern> 32 </servlet-mapping> 33 <servlet-mapping> 34 <servlet-name>RemServlet</servlet-name> 35 <url-pattern>/remServlet</url-pattern> 36 </servlet-mapping> 37 <servlet-mapping> 38 <servlet-name>checkcode</servlet-name> 39 <url-pattern>/checkCodeServlet</url-pattern> 40 </servlet-mapping> 41 42 43 <welcome-file-list> 44 <welcome-file>index.jsp</welcome-file> 45 </welcome-file-list> 46 </web-app>
jdbc.properties配置文件內容
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql:///mydb
user=root
password=123
login.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>My JSP 'login.jsp' starting page</title> 7 <script type="text/javascript"> 8 function changeImg(){ 9 document.getElementById("img").src = "/colloquy/checkCodeServlet?time="+new Date().getTime(); 10 } 11 function changeImg2(obj){ 12 obj.src = "/colloquy/checkCodeServlet?time="+new Date().getTime(); 13 } 14 </script> 15 </head> 16 <body> 17 <% 18 //1.獲取所有cookie 19 Cookie[] cs = request.getCookies(); 20 String username = ""; 21 String password = ""; 22 //2.遍歷cookie數組 23 if(cs != null){ 24 for(Cookie c : cs){ 25 //獲取名稱 26 String name = c.getName(); 27 if("username".equals(name)){ 28 username = c.getValue(); 29 } 30 if("password".equals(name)){ 31 password = c.getValue(); 32 } 33 } 34 } 35 %> 36 37 <form action="/colloquy/loginServlet" method="post"> 38 <table align="center" bgcolor="pink"> 39 <caption>用戶登陸</caption> 40 <tr> 41 <td>用戶名:</td> 42 <td><input type="text" name="username"></td> 43 </tr> 44 <tr> 45 <td>密碼:</td> 46 <td><input type="password" name="password"></td> 47 </tr> 48 <tr> 49 <td>驗證碼:</td> 50 <td><input type="text" name="checkCode"></td> 51 <td><img src="/colloquy/checkCodeServlet" id="img" onclick="changeImg2(this);"></td> 52 <td><a href="javascript:void(0);" onclick="changeImg();">看不清?</a><br></td> 53 <tr> 54 <tr> 55 <td>記住密碼</td> 56 <td><input type="checkbox" name="rem"></td> 57 </tr> 58 <tr> 59 <td colspan="2" align="center" ><input type="submit" value="登陸"></td> 60 </tr> 61 </table> 62 </form> 63 <div align="center" style="color:red;"><%=request.getAttribute("msg")==null ? "" : request.getAttribute("msg") %></div> 64 <div align="center" style="color:#FF0000;"><%=session.getAttribute("regist_msg")==null ? "" : session.getAttribute("regist_msg") %></div> 65 </body> 66 </html>
success.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>My JSP 'success.jsp' starting page</title> 7 </head> 8 <body> 9 10 <%= 11 request.getAttribute("username") 12 %>,歡迎您! 13 14 </body> 15 </html>
所使用的MySQL語句
1 -- 創建用戶信息表 user,並指定主鍵且自增長 2 CREATE TABLE USER( 3 uid INT PRIMARY KEY AUTO_INCREMENT, 4 username VARCHAR(32), 5 userpassword VARCHAR(32) 6 ); 7 8 -- 查詢所有列 9 SELECT * FROM USER; 10 11 -- 添加數據 12 INSERT INTO USER(username,userpassword) VALUE ('zhangsan','123'); 13 INSERT INTO USER(username,userpassword) VALUE ('lisi','1234'); 14 INSERT INTO USER(username,userpassword) VALUE ('wangwu','234'); 15 INSERT INTO USER(username,userpassword) VALUE ('zhaoliu','1234'); 16 INSERT INTO USER(username,userpassword) VALUE ('sisi','234');