Session

作者: 蛋炒饭_By | 来源:发表于2018-03-28 16:42 被阅读9次

    Session简单介绍

    在WEB开发中,服务器可以为每个浏览器用户创建一个会话对象(session对象),注意:一个浏览器用户独占一个session对象(默认情况下)。因此,在需要保存用户数据时,服务器程序可以把用户数据写到浏览器用户独占的session中,当用户使用浏览器访问该web应用的其它servlet时,其它servlet可以从用户的session中取出该用户的数据,为用户服务,从而实现数据在多个页面中的共享。

    Session和Cookie的主要区别

    • Cookie是把用户的数据写到用户的浏览器。
    • Session技术把用户的数据写到用户独占的session中,tomcat服务器内存中。
    • Session对象由服务器创建,开发人员可以调用request对象的getSession方法得到session对象

    session机制演示图

    image

    服务器通过request对象的getSession方法创建出session对象后,会把session的id号,以cookie的形式回写给客户机,这样,只要客户机的浏览器不关,再去访问服务器时,都会带着session的id号去,服务器发现客户机浏览器带session id过来了,就会使用内存中与之对应的session为之服务。

    一个例子

    @WebServlet(name = "TestServlet",urlPatterns = "/test")
    public class TestServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession httpSession = request.getSession();
            httpSession.setAttribute("user","zhangsan");
            System.out.println(httpSession.getId());
        }
    }
    
    

    在开发者工具中查看,第一发出时请求响应头当中有Set-Cooie

    [图片上传失败...(image-b4a782-1522140034760)]

    再次请求时(刷新),响应头当中将没有Set-Cookie,而请求头当中将有Cookie发回给服务器,

    [图片上传失败...(image-b480bb-1522140034760)]

    两个Cookie完全一样,以后的每次请求都会找到那个session对象,完成跟踪。

    Session cookie

    session通过SessionID来区分不同的客户, session是以cookie为基础的,系统会创造一个名为JSESSIONID的输出cookie,这称之为session cookie,以区别persistent cookies(也就是我们通常所说的cookie),session cookie是存储于浏览器内存中的,并不是写到硬盘上的,session cookie针对某一次会话而言,会话结束session cookie也就随着消失了,而persistent cookie只是存在于客户端硬盘上的一段文本。

    关闭浏览器,只会使浏览器端内存里的session cookie消失,但不会使保存在服务器端的session对象消失,同样也不会使已经保存到硬盘上的持久化cookie消失。

    持久化session cookie

    @WebServlet(name = "TestServlet",urlPatterns = "/test")
    public class TestServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession httpSession = request.getSession();
            Cookie cookie = new Cookie("JESSIONID",httpSession.getId());
            cookie.setMaxAge(300);
        }
    }
    
    

    关闭浏览器,5分钟之内打开浏览器,session依然有效。

    HttpSession的生命周期

    问题:用户开一个浏览器访问一个网站,服务器是不是针对这次会话创建一个session?
    答:不是的。session的创建时机是在程序中第一次去执行request.getSession();这个代码,服务器才会为你创建session。
    问题:关闭浏览器,会话结束,session是不是就销毁了呢?
    答:不是的。session是30分钟没人用了才会死,服务器会自动摧毁session。

    session何时会销毁

    A.调用invalidate()方法,该方法使HttpSession立即失效

    @WebServlet(name = "TestServlet",urlPatterns = "/test")
    public class TestServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession httpSession = request.getSession();
            httpSession.invalidate();
        }
    }
    
    

    B.服务器卸载了当前WEB应用

    C.超出session过期时间

    @WebServlet(name = "TestServlet",urlPatterns = "/test")
    public class TestServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession httpSession = request.getSession();
            httpSession.setMaxInactiveInterval(30);//单位秒
        }
    }
    
    

    web.xml文件中也可以修改session的过期时间(全局的,所有的session的过期时间,若想单独设置还是像上面那样单独设置),单位分钟。

     <session-config>
            <session-timeout>30</session-timeout>
     </session-config>
    
    

    利用session完成用户登陆

    首先创建代表用户的JavaBean——User.java。

    public class User {
        private String username;
        private String password;
    
        public User() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        public User(String username, String password) {
            super();
            this.username = username;
            this.password = password;
        }
    
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    
    }
    
    

    然后创建网站首页——index.jsp。

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        欢迎您:${user.username }&nbsp;&nbsp;&nbsp;<a href="/day07/login.html">登录</a>&nbsp;&nbsp;&nbsp;<a href="/day07/LogoutServlet">退出登录</a>
        <br/><br/><br/>
        <a href="/day07/SessionDemo1">购买</a><br/>
        <a href="/day07/SessionDemo2">结账</a>
    </body>
    </html>
    
    

    接着创建登录页面——login.html。

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <form action="/day07/LoginServlet" method="post">
            用户名:<input type="text" name="username"><br/>
            密码:<input type="password" name="password"><br/>
            <input type="submit" value="登录">
        </form>
    </body>
    </html>
    
    

    再创建处理用户登录的Servlet——LoginServlet。

    public class LoginServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
    
            String username = request.getParameter("username");
            String password = request.getParameter("password");
    
            List<User> list = DB.getAll();
            for(User user : list) {
                // 用户登录成功
                if(user.getUsername().equals(username) && user.getPassword().equals(password)) {
                    request.getSession().setAttribute("user", user); // 登录成功,向session中存入一个登录标记
                    response.sendRedirect("/day07/index.jsp");
                    return;
                }
            }
    
            out.print("用户名或密码不正确!!!");
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    
    class DB {
        public static List<User> list = new ArrayList<User>();
    
        static {
            list.add(new User("aaa", "123"));
            list.add(new User("bbb", "123"));
            list.add(new User("ccc", "123"));
        }
    
        public static List<User> getAll() {
            return list;
        }
    }
    
    

    最后创建用户注销的Servlet——LogoutServlet。

    // 完成用户注销
    public class LogoutServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            HttpSession session = request.getSession(false);
            if(session == null) {
                response.sendRedirect("/day07/index.jsp");
                return;
            }
    
            session.removeAttribute("user"); // 移除登录标记
            response.sendRedirect("/day07/index.jsp");
    
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    
    

    使用Session实现验证码

    Session的典型案例:一次性验证码

    生成验证码图像的工具类GenerateCode.java 代码

    package util;
    
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.util.Random;
    
    /**
     * Created by ttc on 2018/3/15.
     */
    public class GenerateCode {
    
        //设置验证图片的宽度, 高度, 验证码的个数
        private int width = 152;
        private int height = 40;
    
        //验证码字体的高度
        private int fontHeight = 38;
    
        //验证码中的单个字符基线. 即:验证码中的单个字符位于验证码图形左上角的 (codeX, codeY) 位置处
        private int codeX = 25;//width / (codeCount + 2);
        private int codeY = 36;
    
        public BufferedImage Generate(String code)
        {
            //定义一个类型为 BufferedImage.TYPE_INT_BGR 类型的图像缓存
            BufferedImage buffImg = null;
            buffImg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    
            //在 buffImg 中创建一个 Graphics2D 图像
            Graphics2D graphics = null;
            graphics = buffImg.createGraphics();
    
            //设置一个颜色, 使 Graphics2D 对象的后续图形使用这个颜色
            graphics.setColor(Color.WHITE);
    
            //填充一个指定的矩形: x - 要填充矩形的 x 坐标; y - 要填充矩形的 y 坐标; width - 要填充矩形的宽度; height - 要填充矩形的高度
            graphics.fillRect(0, 0, width, height);
    
            //创建一个 Font 对象: name - 字体名称; style - Font 的样式常量; size - Font 的点大小
            Font font = null;
            font = new Font("", Font.BOLD, fontHeight);
            //使 Graphics2D 对象的后续图形使用此字体
            graphics.setFont(font);
    
            graphics.setColor(Color.BLACK);
    
            //绘制指定矩形的边框, 绘制出的矩形将比构件宽一个也高一个像素
            graphics.drawRect(0, 0, width - 1, height - 1);
    
            //随机产生 15 条干扰线, 使图像中的认证码不易被其它程序探测到
            Random random = null;
            random = new Random();
            graphics.setColor(Color.GREEN);
            for(int i = 0; i < 30; i++){
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int x1 = random.nextInt(20);
                int y1 = random.nextInt(20);
                graphics.drawLine(x, y, x + x1, y + y1);
            }
    
            graphics.setColor(Color.BLACK);
            for(int i = 0; i < code.length(); i++){
    
                //用随机产生的颜色将验证码绘制到图像中
    //            graphics.setColor(Color.BLUE);
                graphics.drawString(String.valueOf(code.charAt(i)), (i + 1)* codeX, codeY);
            }
    
            return buffImg;
        }
    }
    
    

    ValidateColorServlet

    
    @WebServlet("/validateColorServlet")
    public class ValidateColorServlet extends HttpServlet {
        private int codeCount = 4;
    
        //验证码由哪些字符组成
        char [] codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz23456789".toCharArray();
    
        public void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            //创建 randomCode 对象, 用于保存随机产生的验证码, 以便用户登录后进行验证
            StringBuffer randomCode = new StringBuffer();
            Random random = new Random();
            for(int i = 0; i < codeCount; i++){
                //得到随机产生的验证码数字
                String strRand = null;
                strRand = String.valueOf(codeSequence[random.nextInt(36)]);
                randomCode.append(strRand);
            }
    
            GenerateCode generateCode = new GenerateCode();
            BufferedImage buffImg =generateCode.Generate(randomCode.toString());
    
            request.getSession().setAttribute("CHECK_CODE", randomCode.toString());
    
            //禁止图像缓存
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
    
            //将图像输出到输出流中
            ServletOutputStream sos = null;
            sos = response.getOutputStream();
            ImageIO.write(buffImg, "jpeg", sos);
            sos.close();
    
        }
    }
    
    

    check.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <form action="checkCodeServlet" method="post">
            username:<input type="text" name="username">
            checkCode:<input type="text" name="check">
            <img src="${pageContext.request.contextPath }/validateColorServlet">
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    
    

    CheckCodeServlet

    package com.neusoft.javaweb.checkcode;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class CheckCodeServlet
     */
    @WebServlet("/checkCodeServlet")
    public class CheckCodeServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String strCheckCode = request.getParameter("check");
            String checkCode = (String)request.getSession().getAttribute("CHECK_CODE");
    
            if(strCheckCode.equalsIgnoreCase(checkCode)) {
                response.sendRedirect("hello.jsp");
            }else {
                response.setContentType("text/html");
                response.setCharacterEncoding("utf-8");
                PrintWriter pr = response.getWriter();
                pr.println("验证码错误");
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:Session

          本文链接:https://www.haomeiwen.com/subject/tdsscftx.html