相关推荐recommended
Session详解,学习 Session对象一篇文章就够了
作者:mmseoamin日期:2023-11-30

目录

1 Session概述

2 Session原理

3 Session使用

3.1 获取Session

3.2 Session保存数据

3.3 Session获取数据

3.4 Session移除数据

4 Session与Request应用区别

4.1 Session和request存储数据

4.2 获取session和request中的值

4.3 session和request区别效果

5 Session的声明周期

5.1 Session有效时间设置

5.2 session销毁

.6 浏览器禁用Cookie解决方案(了解)

6.1 浏览器禁用Cookie的后果

6.2 URL重写

6.3 实现URL重写

7 Session实战权限验证

7.1 创建管理员表manager并添加数据

7.2 创建Web项目

7.3 基础环境搭建

7.4 登录页面

7.5 LoginMgrController

7.6 ShowAllManagerController

7.7 ShowAllManagerJsp

8 Session实战保存验证码

8.1 创建验证码

8.2 登录页面

8.3 LoginMgrController

8.4 ShowAllManagerController

今天的分享就到此结束了

创作不易点赞评论互关三连


1 Session概述

(1)Session用于记录用户的状态。Session指的是一段时间内,单个客户端与Web服务器的一连串相关的交互过程。

(2)在一个Session中,客户可能会多次请求访问同一个资源,也有可能请求访问各种不同的服务器资源。

(3)Session是由服务器端创建的

2 Session原理

(1)Session会为每一次会话分配一个Session对象

(2)同一个浏览器发起的多次请求,同属于一次会话(Session)

(3)首次使用到Session时,服务器会自动创建Session,并创建Cookie存储SessionId发送回客户端

3 Session使用

Session作用域:拥有存储数据的空间,作用范围是一次会话有效

  • 一次会话是使用同一浏览器发送的多次请求。一旦浏览器关闭,则结束会话

  • 可以将数据存入Session中,在一次会话的任意位置进行获取

  • 可传递任何数据(基本数据类型、对象、集合、数组)

    3.1 获取Session

    Session是服务器端自动创建的,通过request对象获取

    package com.cxyzxc.www.servlet01;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    @WebServlet(name = "SessionServlet01", value = "/SessionServlet01")
    public class SessionServlet01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象,首次使用到Session时,服务器会自动创建Session,并创建Cookie存储SessionId发送回客户端
            HttpSession session = request.getSession();
            System.out.println("ID:" + session.getId());//唯一标记
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    Session详解,学习 Session对象一篇文章就够了,第1张

    3.2 Session保存数据

    使用setArrtibute(属性名,Object)保存数据到session中

    package com.cxyzxc.www.servlet01;
    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(name = "SessionServlet02", value = "/SessionServlet02")
    public class SessionServlet02 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象,首次使用到Session时,服务器会自动创建Session,并创建Cookie存储SessionId发送回客户端
            HttpSession session = request.getSession();
            //将数据存储以键值对的形式到session对象中,可传递任何数据(基本数据类型、对象、集合、数组)
            session.setAttribute("username","张三");
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

     

    3.3 Session获取数据

    (1)使用getAttribute("属性名");获取session中数据。

    (2)先访问SessionServlet02将数据存储到session对象中,然后通过GetSessionValueServlet01请求获取session中的数据

    package com.cxyzxc.www.servlet01;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    @WebServlet(name = "GetSessionValueServlet01", value = "/GetSessionValueServlet01")
    public class GetSessionValueServlet01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象
            HttpSession session = request.getSession();
            //获取session对象中的值,获取的值是Object类型,转换为其对应的类型
            String username = (String) session.getAttribute("username");
            System.out.println("session对象中存储的username值:" + username);
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    Session详解,学习 Session对象一篇文章就够了,第2张

    3.4 Session移除数据

    (1)使用removeAttribute("属性名");从session中删除数据

    (2)向请求SessionServlet02向session对象中存储数据,然后访问GetSessionValueServlet01可以获取session对象中的值,再访问SessionServlet03移除session对象中存储的数据,最后访问GetSessionValueServlet01获取session对象中的值为null

    package com.cxyzxc.www.servlet01;
    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(name = "SessionServlet03", value = "/SessionServlet03")
    public class SessionServlet03 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象,首次使用到Session时,服务器会自动创建Session,并创建Cookie存储SessionId发送回客户端
            HttpSession session = request.getSession();
            //通过键移除session作用域中的值
            session.removeAttribute("username");
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

     Session详解,学习 Session对象一篇文章就够了,第3张

    4 Session与Request应用区别

    (1)request是一次请求有效,请求改变,则request改变

    (2)session是一次会话有效,浏览器改变,则session改变

    4.1 Session和request存储数据

    package com.cxyzxc.www.servlet01;
    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(name = "SessionServlet04", value = "/SessionServlet04")
    public class SessionServlet04 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象
            HttpSession session = request.getSession();
            //使用session存储数据
            session.setAttribute("username","zhangsan");
            //使用request存储数据
            request.setAttribute("password","123456");
            //重定向
            response.sendRedirect("/webProject10_war_exploded/GetSessionValueServlet01");
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

     

    4.2 获取session和request中的值

    package com.cxyzxc.www.servlet01;
    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(name = "GetSessionValueServlet01", value = "/GetSessionValueServlet01")
    public class GetSessionAndRequestValueServlet01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象
            HttpSession session = request.getSession();
            //获取session对象中的值,获取的值是Object类型,转换为其对应的类型
            String username = (String) session.getAttribute("username");
            //获取request对象中的值,获取的值是Object类型,转换为其对应的类型
            String password = (String) request.getAttribute("password");
            System.out.println("session对象中存储的username值:" + username);
            System.out.println("request对象中存储的password值:" + password);
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    4.3 session和request区别效果

    Session详解,学习 Session对象一篇文章就够了,第4张

    5 Session的声明周期

    1. 开始

      第一次使用到Session的请求产生,则创建Session

    2. 结束

      • 浏览器关闭,则失效

      • Session超时,则失效

        session.setMaxInactiveInterval(seconds);//设置最大有效时间(单位:秒)

      • 手工销毁,则失效

        session.invalidate();//登录退出,销毁

    5.1 Session有效时间设置

    SessionServlet05类设置session有效期为20秒,先通过请求SessionServlet05类将session存储在,然后在20秒内第一次在GetSessionValueServlet02获取sessionID值,与SessionServlet05类中输出的id值一致,过20秒后在GetSessionValueServlet02类中输出的sessionID值不一致了

     

    package com.cxyzxc.www.servlet01;
    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(name = "SessionServlet05", value = "/SessionServlet05")
    public class SessionServlet05 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象,首次使用到Session时,服务器会自动创建Session,并创建Cookie存储SessionId发送回客户端
            HttpSession session = request.getSession();
            //设置session有效期,时间单位为秒
            session.setMaxInactiveInterval(20);
            //输出sessionid值
            System.out.println("SessionServlet05类中输出ID:"+session.getId());
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    Session详解,学习 Session对象一篇文章就够了,第5张

    5.2 session销毁

    先使用GetSessionValueServlet03类获取session的id值,然后使用GetSessionValueServlet04类获取session的id值,两个类获取的id值一致,在GetSessionValueServlet04类中输出id值后销毁了session,然后再在GetSessionValueServlet03类中获取id值,就不一致了,就是服务器新建的session对象了

    5.2.1 GetSessionValueServlet03类

    package com.cxyzxc.www.servlet01;
    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(name = "GetSessionValueServlet03", value = "/GetSessionValueServlet03")
    public class GetSessionValueServlet03 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象
            HttpSession session = request.getSession();
            //输出sessionid值
            System.out.println("GetSessionValueServlet03类中输出ID:"+session.getId());
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

     

    5.2.2 GetSessionValueServlet04类

    package com.cxyzxc.www.servlet01;
    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(name = "GetSessionValueServlet04", value = "/GetSessionValueServlet04")
    public class GetSessionValueServlet04 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象
            HttpSession session = request.getSession();
            //输出sessionid值
            System.out.println("GetSessionValueServlet04类中输出ID:"+session.getId());
            //销毁session
            session.invalidate();
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    Session详解,学习 Session对象一篇文章就够了,第6张

    .6 浏览器禁用Cookie解决方案(了解)

    6.1 浏览器禁用Cookie的后果

    服务器在默认情况下,会使用Cookie的方式将sessionID发送给浏览器,如果用户禁止Cookie,则sessionID不会被浏览器保存,此时,服务器可以使用URL重写这样的方式来发送sessionID

     Session详解,学习 Session对象一篇文章就够了,第7张

    多次请求GetSessionValueServlet05类输出的session的id值都不相同,并且在网站的Cookie对象中没有session的id值存在

    Session详解,学习 Session对象一篇文章就够了,第8张 

    6.2 URL重写

    浏览器在访问服务器上的某个地址时,不再使用原来的那个地址,而是使用经过改写的地址(即在原来的地址后面加上了sessionID)

    6.3 实现URL重写

    response.encodeRedirectURL(String url)生成重写的URL

    6.3.1 重写URL

    package com.cxyzxc.www.servlet01;
    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(name = "GetSessionValueServlet06", value = "/GetSessionValueServlet06")
    public class GetSessionValueServlet06 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象
            HttpSession session = request.getSession();
            //输出sessionid值
            System.out.println("GetSessionValueServlet06类中输出ID:"+session.getId());
            //重写URL追加session值
            String newURL = response.encodeURL("/webProject10_war_exploded/GetSessionValueServlet07");
            System.out.println("重写后的URL:"+newURL);
            //重定向
            response.sendRedirect(newURL);
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

     

    6.3.1 获取session

    package com.cxyzxc.www.servlet01;
    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(name = "GetSessionValueServlet07", value = "/GetSessionValueServlet07")
    public class GetSessionValueServlet07 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置请求参数的编码格式,这种方式对get请求方式无效
            request.setCharacterEncoding("UTF-8");
            //设置响应编码格式为UTF-8
            response.setContentType("text/html;charset=UTF-8");
            //获取Session对象
            HttpSession session = request.getSession();
            //输出sessionid值
            System.out.println("GetSessionValueServlet07类中输出ID:"+session.getId());
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    Session详解,学习 Session对象一篇文章就够了,第9张

    7 Session实战权限验证

    Session详解,学习 Session对象一篇文章就够了,第10张 

    7.1 创建管理员表manager并添加数据

    Session详解,学习 Session对象一篇文章就够了,第11张 

    7.2 创建Web项目

    创建Web项目,导入相关jar包

    • commons-dbutils-1.7.jar

    • druid-1.1.5.jar

    • mysql-connector-java-5.1.25-bin.jar

    • servlet-api.jar

      7.3 基础环境搭建

      在项目下创建包目录结构如下

      • com.cxyzxc.www.controller包:调用业务逻辑Servlet

      • com.cxyzxc.www.dao包:数据访问层接口

      • com.cxyzxc.www.dao.impl包:数据访问层接口实现类

      • com.cxyzxc.www.entity包:实体类

      • com.cxyzxc.www.jsp包:打印显示页面Servlet

      • com.cxyzxc.www.service包:业务逻辑层接口

      • com.cxyzxc.www.service.impl包:业务逻辑层接口实现类

      • com.cxyzxc.www.utils包:工具类

      • database.properties:数据库连接及连接池配置文件

        7.4 登录页面

        7.4.1 login.html

        
        
            
                
                管理员登录页面
                
            
            
                
                    

        账号:

        密码:

         

        7.4.2 login.css

        * {
            margin: 0;
            padding: 0;
        }
        div {
            width: 400px;
            background-color: #ccc;
            margin: 30px auto;
            padding-top: 30px;
            text-align: center;
        }
        p {
            margin-top: 10px;
        }
        input {
            outline: none;
        }

        7.5 LoginMgrController

        package com.cxyzxc.www.controller;
        import com.cxyzxc.www.entity.Manager;
        import com.cxyzxc.www.service.ManagerService;
        import com.cxyzxc.www.service.impl.ManagerServiceImpl;
        import javax.servlet.*;
        import javax.servlet.http.*;
        import javax.servlet.annotation.*;
        import java.io.IOException;
        @WebServlet(name = "LoginMgrController", value = "/LoginMgrController")
        public class LoginMgrController extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //1、处理乱码
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                //2、收参(获取客户端发送过来的请求数据)
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                //3、调用业务方法
                ManagerService managerService = new ManagerServiceImpl();
                Manager manager = managerService.login(username, password);
                //4、处理结果,根据结果做不同的跳转
                if (manager != null) {//manager不为null,说明账号和密码正确,登录成功
                    //将获取的账号和密码信息存储在session中
                    HttpSession session = request.getSession();
                    session.setAttribute("manager", manager);
                    //跳转到显示所有管理员信息的Servlet
                    response.sendRedirect("/managerProject01_war_exploded/ShowAllManagerController");
                } else {//manager为null。说明账号或者密码错误,登录失败
                    response.sendRedirect("/managerProject01_war_exploded/login.html");
                }
            }
            @Override
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
            }
        }

        7.6 ShowAllManagerController

        package com.cxyzxc.www.controller;
        import com.cxyzxc.www.entity.Manager;
        import com.cxyzxc.www.service.ManagerService;
        import com.cxyzxc.www.service.impl.ManagerServiceImpl;
        import javax.servlet.*;
        import javax.servlet.http.*;
        import javax.servlet.annotation.*;
        import java.io.IOException;
        import java.util.List;
        @WebServlet(name = "ShowAllManagerController", value = "/ShowAllManagerController")
        public class ShowAllManagerController extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //1、处理乱码
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                //通过HttpSession完成权限控制
                HttpSession session =request.getSession();
                //获取session中存储的值
                Manager manager = (Manager)session.getAttribute("manager");
                //判断获取的值
                if(manager!=null){
                    //调用业务,只做业务,业务与显示分离
                    ManagerService managerService = new ManagerServiceImpl();
                    List managers =managerService.showAllManager();
                    //将获取的数据存储在request作用域中
                    request.setAttribute("managers",managers);
                    //转发,跳转到显示结果的Servlet
                    request.getRequestDispatcher("/ShowAllManagerJsp").forward(request,response);
                }else{
                    //说明没有登录,要先去登录才能进行显示
                    response.sendRedirect("/managerProject01_war_exploded/login.html");
                }
            }
            @Override
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
            }
        }

        7.7 ShowAllManagerJsp

        package com.cxyzxc.www.jsp;
        import com.cxyzxc.www.entity.Manager;
        import javax.servlet.*;
        import javax.servlet.http.*;
        import javax.servlet.annotation.*;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.util.List;
        @WebServlet(name = "ShowAllManagerJsp", value = "/ShowAllManagerJsp")
        public class ShowAllManagerJsp extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //1、处理乱码
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                //2、获取数据
                List managers = (List) request.getAttribute("managers");
                //获取输出流
                PrintWriter printWriter = response.getWriter();
                if (managers.size() != 0) {
                    printWriter.println("");
                    printWriter.println("");
                    printWriter.println("所有管理员");
                    printWriter.println("");
                    printWriter.println("");
                    printWriter.println("");
                    printWriter.println("");
                    printWriter.println(" ");
                    printWriter.println(" ");
                    printWriter.println(" ");
                    printWriter.println(" ");
                    printWriter.println(" ");
                    for (int i = 0; i < managers.size(); i++) {
                        printWriter.println("");
                        printWriter.println("");
                        printWriter.println("");
                        printWriter.println("");
                        printWriter.println("");
                        printWriter.println("");
                    }
                    printWriter.println("
        序号账号密码操作
        " + (i + 1) + "" + managers.get(i).getUsername() + "" + managers.get(i).getPassword() + "修改 删除
        "); printWriter.println(""); } else { printWriter.println("

        数据库中没有数据查询

        "); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

        8 Session实战保存验证码

        生成验证码的方式有很多种,可以使用随机数的方式实现,也可以使用ValidateCode类来实现(需要导入ValidateCode.jar包)。在这里,我们学习使用ValidateCode类来生成验证码

        8.1 创建验证码

        package com.cxyzxc.www.controller;
        import cn.dsna.util.images.ValidateCode;
        import javax.servlet.*;
        import javax.servlet.http.*;
        import javax.servlet.annotation.*;
        import java.io.IOException;
        /**
         * 此Servlet的作用是生成验证码并将生成的验证码存储到session中、发送到页面中显示
         */
        @WebServlet(name = "VerificationServlet", value = "/VerificationServlet")
        public class VerificationServlet extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //设置验证码规格
                ValidateCode validateCode = new ValidateCode(200, 20, 4, 10);
                //获取验证码
                String code = validateCode.getCode();
                //将验证码存储在session中
                HttpSession session = request.getSession();
                session.setAttribute("code",code);
                //将验证码输出到客户端
                validateCode.write(response.getOutputStream());
            }
            @Override
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
            }
        }

        8.2 登录页面

        
        
            
                
                管理员登录页面
                
            
            
                
                    

        账号:

        密码:

        验证码: Session详解,学习 Session对象一篇文章就够了,第12张

        8.3 LoginMgrController

        package com.cxyzxc.www.controller;
        import com.cxyzxc.www.entity.Manager;
        import com.cxyzxc.www.service.ManagerService;
        import com.cxyzxc.www.service.impl.ManagerServiceImpl;
        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(name = "LoginMgrController", value = "/LoginMgrController")
        public class LoginMgrController extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //1、处理乱码
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                //2、收参(获取客户端发送过来的请求数据)
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                String inputCodde = request.getParameter("verification");
                //获取session中的验证码
                HttpSession session = request.getSession();
                String codes = (String) session.getAttribute("code");
                if (!inputCodde.isEmpty() && inputCodde.equalsIgnoreCase(codes)) {
                    //3、调用业务方法
                    ManagerService managerService = new ManagerServiceImpl();
                    Manager manager = managerService.login(username, password);
                    //4、处理结果,根据结果做不同的跳转
                    if (manager != null) {//manager不为null,说明账号和密码正确,登录成功
                        //将获取的账号和密码信息存储在session中
                        HttpSession session2 = request.getSession();
                        session2.setAttribute("manager", manager);
                        //跳转到显示所有管理员信息的Servlet
                        response.sendRedirect("/managerProject02_war_exploded/ShowAllManagerController");
                    } else {//manager为null。说明账号或者密码错误,登录失败
                        response.sendRedirect("/managerProject02_war_exploded/login.html");
                    }
                } else {//验证码不对,重新登录
                    response.sendRedirect("/managerProject02_war_exploded/login.html");
                }
            }
            @Override
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
            }
        }

        8.4 ShowAllManagerController

        package com.cxyzxc.www.controller;
        import com.cxyzxc.www.entity.Manager;
        import com.cxyzxc.www.service.ManagerService;
        import com.cxyzxc.www.service.impl.ManagerServiceImpl;
        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;
        import java.util.List;
        @WebServlet(name = "ShowAllManagerController", value = "/ShowAllManagerController")
        public class ShowAllManagerController extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //通过HttpSession完成权限控制
                HttpSession session =request.getSession();
                //获取session中存储的值
                Manager manager = (Manager)session.getAttribute("manager");
                //判断获取的值
                if(manager!=null){
                    //调用业务,只做业务,业务与显示分离
                    ManagerService managerService = new ManagerServiceImpl();
                    List managers =managerService.showAllManager();
                    //将获取的数据存储在request作用域中
                    request.setAttribute("managers",managers);
                    //转发,跳转到显示结果的Servlet
                    request.getRequestDispatcher("/ShowAllManagerJsp").forward(request,response);
                }else{
                    //说明没有登录,要先去登录才能进行显示
                    response.sendRedirect("/managerProject02_war_exploded/login.html");
                }
            }
            @Override
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
            }
        }

        今天的分享就到此结束了

        创作不易点赞评论互关三连

         Session详解,学习 Session对象一篇文章就够了,第13张