(13)session和cookie的原理分析,完成(免)登录和安全退出功能

关于B/S结构系统的会话机制

三种域对象

这三个域对象的大小关系: request < session < application, 尽量使用小的域

  • request 请求域(请求级别的), 对应的类名:HttpServletRequest
  • session会话域(用户级别的), 对应的类名:HttpSession
  • application应用域(项目级别的,所有用户共享的)对应的类名:ServletContext
  • 三个域对象都有三个公共的方法: setAttribute(向域当中绑定数据), getAttribute(从域当中获取数据), removeAttribute(删除域当中的数据)

HttpSession

一个会话当中包含多次请求(一次会话对应N次请求)

  • 一次会话对应服务器端的session对象: 用户打开浏览器进行的一系列操作然后最终将浏览器关闭的整个过程,可以认为是一次会话
  • 一次请求对应服务器端的request对象:用户在浏览器上点击了一下然后到页面停下来,可以认为是一次请求

jarkata.servlet.http.HttpSessionsession对象用来保存会话状态(用户登录成功是一种登录成功的状态,使用session对象可以保留这种会话状态)

  • 因为HTTP协议是一种无状态协议 ,请求的瞬间B和S是连接的,但是请求结束之后,连接就断了,这样可以降低服务器的压力
  • 由于B和S断开了所以服务器是不知道浏览器什么时候关闭的, 就不会销毁session对象
  • session机制属于B/S结构的一部分是一个规范, 不同的语言开发web项目对这种会话机制都有实现

在这里插入图片描述

request请求域(HttpServletRequest), application应用域(ServletContext)不被用来保存会话状态

  • reques对象是浏览器发起请求的时候创建,请求结束之后销毁, 请求域的作用域太小并且保存的数据在下次请求中就不能拿来使用
  • ServletContext对象是服务器启动的时候创建,服务器关闭的时候销毁,应用域的作用域太大

HttpSession对象创建和销毁的时机(js内置一个session对象并有其对应的Cookie对象(JSESSIONID=xxx), 不需要等到服务器生成返回就可以在jsp页面中使用)

  • 用户发起第一次请求, 服务器端获取session对象,如果没有则新建同时生成对应的Cookie对象(JSESSIONID=xxx)返回给浏览器
  • session对象对应的Cookie对象(JSESSIONID=xxx): JSESSIONID是Cookie对象的name(唯一标识),根据name获取对应的Cookie对象然后获取xxx查找对应的session

在这里插入图片描述

  • 用户发起第二次请求, 浏览器自动将内存中的Cookie对象封装到请求协议中发送给服务器,服务器根据指定name的Cookie对象的value查找session对象(找不到则新建)

在这里插入图片描述

  • 用户关闭浏览器, 内存消失(cookie消失和sessionid都会消失)
  • 重新打开浏览器之后已经没有这个sessionid, 自然无法找到服务器端的session对象,等同于会话结束
  • 服务器虽然不知道用户关闭了浏览器, 但session的销毁时机是依靠session超时机制决定或者点击安全退出手动销毁
// 张三第一次打开浏览器A访问的服务器时候会在服务器端生成张三专属的session对象
// 李四第一次打开浏览器B访问服务器的时候同理生成李四专属的session对象
// 下次获取的时候张三再访问的服务器的获取的session对象就是张三的,李四再访问服务器的时候获取的session对象就是李四的
HttpSession session = request.getSession();
//销毁session对象
session.invalidate()

获取session及其存储数据的方法

HttpServletRequest接口提供的getSession()方法可以用来从服务器端获取当前的session对象,如果没有获取到则新建

  • 当getSession()方法的参数是false时表示如果从服务器端没有获取到session对象并不会新建,而是返回一个null
方法名功能
void setAttribute(String name, Object obj)向会话域当中绑定数据
Object getAttribute(String name)根据name从请求域当中获取数据
void removeAttribute(String name)将会话域当中绑定的数据移除
void invalidate()手动销毁session对象

设置session的超时时长

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <!--如果30分钟过去了,session对象仍然没有被访问,session对象会被销毁-->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>
@WebServlet("/test/session")
public class TestSessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从WEB服务器当中获取session对象,如果没有则新建
        HttpSession session = request.getSession();
        // 获取系统当前时间
		Date nowTime = new Date();
        // 向会话域当中绑定数据
        session.setAttribute("sysTime",nowTime);
        // 从会话域当中取数据
        Object obj = session.getAttribute("sysTime")
        // 将session对象响应到浏览器
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
		out.print("session域当中获取的系统当前时间 = " + obj);
    }
}

Cookie

概述

cookie怎么生成?cookie保存在什么地方?cookie有啥用?浏览器什么时候发送以及发送哪些cookie给服务器?

  • 你每访问一个网站服务器都会给你返回它对应的Cookie对象(name=xxx…)
  • 浏览器会将接收的Cookie对象(name=xxx…)保存在运行内存中(浏览器只要关闭cookie就消失)或硬盘文件中(有效时间结束才会消失)
  • cookie和session机制其实都是为了保存会话的状态: cookie是将会话的状态保存在浏览器客户端上, session是将会话的状态保存在服务器端上
  • 在HTTP协议中规定当浏览器发送请求的时候,会自动携带该请求路径关联的cookie对象给服务器

cookie机制和session机制不是java中的机制而是HTTP协议的一部分, 做web开发不管是什么编程语言cookie和session机制都是需要的

  • HTTP协议中规定:任何一个cookie都是由字符串类型的name(Cookie对象的唯一标识)和value(Cookie对象中存储的数据)的键值对组成
  • session对象对应的Cookie对象(JSESSIONID=xxx): JSESSIONID是Cookie对象的name,根据name获取对应的Cookie对象然后获取xxx查找对应的session

Cookie禁用即服务器正常发送Cookie对象给浏览器但是浏览器不要了,这样每一次浏览器发起请求都没有携带sessionid, 服务器查找不到就会创建新的session对象

  • 禁用了cookie需要使用URL重写机制实现session机制: http://localhost:8080/servlet12/test/session;jsessionid=19D1C99560DCBF84839FA43D58F56E16
  • URL重写机制要求开发人员在编写任何请求路径的时候后面都要添加一个sessionid, 这给开发带来了很大的难度, 所以大部分网站都不允许禁用cookie

cookie的经典案例: 在未登录的情况下向购物车中放几件商品,关闭商城再次打开浏览器访问的时候,购物车中的商品还在

  • 将购物车中的商品编号放到Cookie对象(productIds=xxxxx,yyyy,)中并保存在硬盘文件,下次打开商城自动读取本地硬盘中存储的cookie然后动态展示商品

126邮箱中有一个功能:用户输入正确的用户名和密码,并且同时选择十天内免登录

  • 登录成功后浏览器客户端会保存一个cookie(保存了用户名和密码等信息),这个cookie保存在硬盘文件当中并且十天有效
  • 在十天内用户再次访问126的时候,浏览器自动提交126的关联的cookie给服务器,服务器接收到cookie之后获取用户名和密码验证之后自动登录成功
  • 怎么让cookie失效: 十天过后自动失效, 或者改密码, 或者在客户端浏览器上清除cookie(ctrl + shift + delete)

获取和设置cookie参数的方法

servlet中对cookie提供的支持

  • HttpServletResponse接口提供的addCookie(cookie对象)方法可以把cookie数据发送给浏览器

  • HttpServletRequest接口提供的getCookies()可以获取所有的Cookie,返回值是一个Cookie数组,注意没有cookie的时候返回的是null

jakarta.servlet.http.Cookie提供的设置cookie相关参数的方法

方法名功能
Cookie (key,value)只有一个有参构造方法用来创建Cookie对象
getName()获取cookie的name
getValue()获取cookie的value
setMaxAge(int)设置cookie的有效时间,以秒为单位, cookie.setMaxAge(60 * 60)表示设置cookie在一小时之后失效
setPath(“”)手动设置cookie关联的路径,浏览器上有很多cookie,浏览器发起不同的请求对应路径下关联的cookie才会被提交到服务器

关于cookie的有效时间

  • 没有设置有效时间:默认保存在浏览器的运行内存中,浏览器关闭则cookie消失
  • 只要设置cookie的有效时间 > 0,这个cookie一定会存储到硬盘文件当中
  • 设置cookie的有效时间 = 0 : 删除浏览器上的同名cookie
  • 设置cookie的有效时间 < 0 : 保存在运行内存中和不设置一样

cookie关联的路径: 假设现在的cookie是由发送http://localhost:8080/servlet13/cookie/generate请求路径对应的Servlet生成的

  • cookie默认关联的path, 当发送的请求路径是http://localhost:8080/servlet13/cookie或它的子路径时才会携带这个cookie提交到服务器
  • 手动设置cookie关联的path, cookie.setPath(“/servlet13”)表示只有是/servlet13或者它的子路径才会提交这个cookie到服务器

浏览器发起请求,服务器生成cookie并响应到浏览器
在这里插入图片描述

@WebServlet("/cookie/generate")
public class GenerateCookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 创建Cookie对象
        Cookie cookie = new Cookie("productid", "12345645623145612");
        Cookie cookie2 = new Cookie("username", "zhangsan");

        // 设置cookie的有效期 < 0,表示该cookie不会被存储(表示不会被存储到硬盘文件中,会放在浏览器运行内存当中),和不调用sexMaxAge是同一个效果
        cookie.setMaxAge(-1); 
        cookie2.setMaxAge(-1);

         // 设置cookie的关联路径
        cookie.setPath(request.getContextPath());
        cookie2.setPath(request.getContextPath());

        // 将多个cookie响应到浏览器
        response.addCookie(cookie);
        response.addCookie(cookie2);
    }
}

浏览器发送cookie给服务器了,通过java程序接收浏览器发送过来的cookie
在这里插入图片描述

@WebServlet("/sendCookie")
public class ReceiveCookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 如果浏览器没有提交cookie,这个方法返回值是null,并不是返回一个长度为0的数组
        Cookie[] cookies = request.getCookies();

        // 如果不是null,表示一定有cookie
        if (cookies != null) {
            // 遍历数组
            for (Cookie cookie : cookies) {
                // 获取cookie的name和value
                String name = cookie.getName();
                String value = cookie.getValue();
                System.out.println(name + "=" + value);
            }
        }
    }
}

完善单表的(免)登录退出功能

实现登录功能

步骤1:数据库当中添加一个用户表t_user并向表中插入一条用户数据

  • t_user表当中存储的是用户基本的登录信息: 登录的用户名和登录的密码
  • 密码一般在数据库表当中存储的是密文(MD加密算法) ,一般不以明文的形式存储(这里先使用明文方式)

步骤2:实现一个登录页面的表单(包含用户名和密码输入框) , 用户点击登录时利用表单发起post请求提交用户名和密码

  • request.getContextPath()可以动态的获取一个应用的根路径

步骤3:后台编写一个对应的Servlet处理登录的请求

  • 登录成功:跳转到部门列表页面(登录成功必须获取到session对象,没有session也要新建一个session对象)
  • 登录失败:跳转到提供的登录失败的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录失败</title>
</head>
<body>
	登录失败,请<a href="${pageContext.request.contextPath}/index.jsp">重新登录</a>
</body>
</html>

使用session机制解决用户在不登录的情况下直接通过后端的请求路径访问系统的问题

  • 可以在登录成功之后获取session对象存储用户的登录信息(第一次登录肯定获取不到所以需要新建)
@WebServlet({"/user/login","/user/exit"})
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if("/user/login".equals(servletPath)){
            doLogin(request, response);
        }else if("/user/exit".equals(servletPath)){
            doExit(request, response);
        }
    }

    protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean success = false;
        // 获取用户名和密码验证是否正确,前端提交格式:username=admin&password=123
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 连接数据库验证用户名和密码
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "select * from t_user where username = ? and password = ?";
            // 编译SQL
            ps = conn.prepareStatement(sql);
            // 给?传值
            ps.setString(1, username);
            ps.setString(2, password);
            // 执行SQL
            rs = ps.executeQuery();
            // 这个结果集当中最多只有一条数据
            if (rs.next()) { // 不需要while循环
                // 登录成功
                success = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        // 登录成功/失败
        if (success) {
            // 登录成功必须获取到session对象,没有session也要新建一个session对象
            HttpSession session = request.getSession(); 
            // 把用户信息存到会话域中
            session.setAttribute("username", username);
            // 成功跳转到用户列表页面
            response.sendRedirect(request.getContextPath() + "/dept/list");
        } else {
            // 失败跳转到失败页面
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }
}

当用户通过访问路径的方式访问系统时需要先获取当前的session对象

  • 获取不到返回null不能新建session,session为null说明用户没有登录需要先登录
  • 获取到后判断session对象是否存储的有用户的信息
@WebServlet({"/dept/list", "/dept/detail", "/dept/delete", "/dept/save", "/dept/modify"})
public class DeptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前session对象获取不到返回null
        // 如果直接访问jsp页面可以拿到是jsp内置的session对象
        HttpSession session = request.getSession(false);
        // 获取到session对象并且session中有数据表示用户登录过
        if(session != null && session.getAttribute("username") != null){
            String servletPath = request.getServletPath();
            if("/dept/list".equals(servletPath)){
                doList(request, response);
            }else if("/dept/detail".equals(servletPath)){
                doDetail(request, response);
            }else if("/dept/delete".equals(servletPath)){
                doDel(request, response);
            }else if("/dept/save".equals(servletPath)){
                doSave(request, response);
            }else if("/dept/modify".equals(servletPath)){
                doModify(request, response);
            }
        }else{
            // 跳转到登录页面,访问web站点的根即可,自动找到欢迎页面
            response.sendRedirect(request.getContextPath() + "/index.jsp"); 
        }
    }

cookie实现十天内免登录功能

在登录页面给一个复选框,复选框后面给一句话十天内免登录

  • 用户选择了复选框表示用户想要十天内免登录 , 没有选择复选框表示用户不想使用十天内免登录功能
<%@page contentType="text/html;charset=UTF-8"%>
<%--访问jsp的时候不生成session对象。--%>
<%@page session="false" %>

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>欢迎使用OA系统</title>
	</head>
	<body>
        <h1>LOGIN PAGE</h1>
        <hr>
        <%--前端页面发送请求的时候,请求路径以“/”开始,带项目名。--%>
        <form action="${pageContext.request.contextPath}/user/login" method="post">
            username: <input type="text" name="username" ><br>
            password: <input type="password" name="password"><br>
            <input type="checkbox" name="f" value="1">十天内免登录<br>
            <input type="submit" value="login">
        </form>
	</body>
</html>

如果用户登录成功了,并且用户登录时也选择了十天内免登录功能

  • 在Servlet的login方法中创建cookie用来存储用户名和密码,设置关联路径(项目根目录)和有效期(十天),最后将cookie响应给浏览器
  • 浏览器下次发送这个cookie关联的请求路径时就会携带这个cookie供服务器进行验证
@WebServlet({"/user/login","/user/exit"})
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if("/user/login".equals(servletPath)){
            doLogin(request, response);
        }else if("/user/exit".equals(servletPath)){
            doExit(request, response);
        }
    }
    // 十天内免登录
    protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean success = false;
        // 获取用户名和密码,验证是否正确
        // 前端你是这样提交的:username=admin&password=123
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 连接数据库验证用户名和密码
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "select * from t_user where username = ? and password = ?";
            // 编译SQL
            ps = conn.prepareStatement(sql);
            // 给?传值
            ps.setString(1, username);
            ps.setString(2, password);
            // 执行SQL
            rs = ps.executeQuery();
            // 这个结果集当中最多只有一条数据。
            if (rs.next()) { // 不需要while循环
                // 登录成功
                success = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        // 登录成功/失败
        if (success) {
            // 登录成功必须获取到session对象,没有session也要新建一个session对象
            HttpSession session = request.getSession(); 
            //把用户信息存到会话域中
            session.setAttribute("username", username);
            User user = new User(username, password);
            session.setAttribute("user", user);

            // 登录成功了,并且用户确实选择了“十天内免登录”功能
            String f = request.getParameter("f");
            if("1".equals(f)){
                // 创建Cookie对象存储登录名
                Cookie cookie1 = new Cookie("username", username);
                // 创建Cookie对象存储密码,密码一般不直接存储,真实情况下是加密的
                Cookie cookie2 = new Cookie("password", password); 
                // 设置cookie的有效期为十天
                cookie1.setMaxAge(60 * 60 * 24 * 10);
                cookie2.setMaxAge(60 * 60 * 24 * 10);
                // 设置cookie的path(只要访问这个应用,浏览器就一定要携带这两个cookie)
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                // 响应cookie给浏览器
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            // 成功,跳转到用户列表页面
            response.sendRedirect(request.getContextPath() + "/dept/list");
        } else {
            // 失败,跳转到失败页面
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

用户重新打开浏览器再次访问该网站的时候有两个走向, 要么跳转到部门列表页面或跳转到登录页面 , 这两个走向需要编写java程序进行控制的

  • 获取浏览器中所有的cookie进行遍历,如果存在两个cookie的用户名和密码都正确则直接跳转到部门列表页面, 否则跳转到登录页面
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <!--手动配置默认欢迎页面,默认从应用的根下开始不用加/,当访问根目录时默认发起/oa/welcome请求-->
    <welcome-file-list>
        <welcome-file>welcome</welcome-file>
    </welcome-file-list>
</web-app>
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 这个Cookie[]数组可能是null,如果不是null数组的长度一定是大于0的
        Cookie[] cookies = request.getCookies();
        String username = null;
        String password = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if("username".equals(name)){
                    username = cookie.getValue();
                }else if("password".equals(name)){
                    password = cookie.getValue();
                }
            }
        }

        // 使用username和password变量验证用户名和密码是否正确
        if(username != null && password != null){
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            boolean success = false;
            try {
                conn = DBUtil.getConnection();
                String sql = "select * from t_user where username = ? and password = ?";
                ps = conn.prepareStatement(sql);
                ps.setString(1,username);
                ps.setString(2,password);
                rs = ps.executeQuery();
                if (rs.next()) {
                    // 登录成功
                    success = true;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DBUtil.close(conn, ps, rs);
            }

            if (success) {
                // 获取session
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                User user = new User(username, password);
                session.setAttribute("user", user);
                // 正确,表示登录成功
                response.sendRedirect(request.getContextPath() + "/dept/list");
            }else{
                // 错误,表示登录失败, 跳转到登录页面
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }else{
            // 跳转到登录页面
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }

    }
}

安全退出功能

安全退出的按钮在list.jsp动态响应的内容中: 退出后用户不能直接访问用户列表页面

<h3>欢迎${username},在线人数${onlinecount}人</h3>
<a href="user/exit">[退出系统]</a>
protected void doExit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取并销毁session,这个session可能为null
    HttpSession session = request.getSession(false);
    if (session != null) {
        // 手动销毁session对象
        session.invalidate();
        // 销毁cookie(退出系统将所有的cookie全部销毁)
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 设置cookie的有效期为0,表示删除该cookie
                cookie.setMaxAge(0);
                // 设置cookie的关联路径
                cookie.setPath(request.getContextPath()); // 删除cookie的时候注意路径问题
                // 响应cookie给浏览器,浏览器端会将之前的cookie覆盖
                response.addCookie(cookie);
            }
        }
        // 跳转到登录页面
        response.sendRedirect(request.getContextPath());
    }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值