會話技術: 會話:瀏覽器訪問伺服器端,發送多次請求,接受多次響應。直到有一方斷開連接。會話結束。 解決問題:可以使用會話技術,在一次會話的多次請求之間共用數據。 分類: 客戶端會話技術 Cookie 伺服器端會話技術 Session 客戶端會話技術:Cookie 小餅干的意思 伺服器端不需要管理,方
會話技術:
會話:瀏覽器訪問伺服器端,發送多次請求,接受多次響應。直到有一方斷開連接。會話結束。
解決問題:可以使用會話技術,在一次會話的多次請求之間共用數據。
分類:
客戶端會話技術 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