会话技术( Cookie ,Session)

 会话技术:
    会话:浏览器访问服务器端,发送多次请求,接受多次响应。直到有一方断开连接。会话结束。
    
    解决问题:可以使用会话技术,在一次会话的多次请求之间共享数据。
        
    分类:
        客户端会话技术    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');
原文地址:https://www.cnblogs.com/rongsnow/p/5172246.html