session&cookie(超详细)

Conversat

Conversat即会话技术,

  1. 会话:一次会话中包含多次请求和响应。
  • 一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止
  1. 功能:在一次会话的范围内的多次请求间,共享数据
  2. 方式:
  3. 客户端会话技术:Cookie
  4. 服务器端会话技术:Session
1.cookie
  1. 概念:客户端会话技术,将数据保存到客户端

  2. 快速入门

  • 使用步骤:

    1. 创建Cookie对象,绑定数据
    • new Cookie(String name, String value)
    1. 发送Cookie对象
    • response.addCookie(Cookie cookie)
     @Override
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //创建
         Cookie cookie = new Cookie("msg","hello");
     
         //发送
         response.addCookie(cookie);
     }
    
    1. 获取Cookie,拿到数据
    • Cookie[] request.getCookies()
     @Override
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //获取Cookie
         Cookie[] cs = request.getCookies();
         //获取数据
         if (cs != null) {
             for (Cookie c : cs) {
                 String name = c.getName();
                 String value = c.getValue();
                 System.out.println(name + ":" + value);
             }
         }
     }
    

    4.将Cookie,持久化到磁盘中

    @WebServlet(name = "CDemo03", value = "/CDemo03")
    public class CDemo03 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie cookie = new Cookie("age","21");
            cookie.setMaxAge(300);
            response.addCookie(cookie);
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }
    
  1. 实现原理
  • 基于响应头set-cookie和请求头cookie实现
  1. cookie的细节

    1. 一次可不可以发送多个cookie?
    • 可以
    • 可以创建多个Cookie对象,使用response调用多次addCookie方法发送cookie即可。
    1. cookie在浏览器中保存多长时间?
    2. 默认情况下,当浏览器关闭后,Cookie数据被销毁
    3. 持久化存储:
     * setMaxAge(int seconds)
       1. 正数:将Cookie数据写到硬盘的文件中。持久化存储。并指定cookie存活时间,时间到后,cookie文件自动失效
       2. 负数:默认值
       3. 零:删除cookie信息
    
    1. cookie能不能存中文?
    • 在tomcat 8 之前 cookie中不能直接存储中文数据。
      • 需要将中文数据转码—一般采用URL编码(%E3)
    • 在tomcat 8 之后,cookie支持中文数据。特殊字符还是不支持,建议使用URL编码存储,URL解码解析
    1. cookie共享问题?
    2. 假设在一个tomcat服务器中,部署了多个web项目,那么在这些web项目中cookie能不能共享?
     * 默认情况下cookie不能共享
    
     * setPath(String path):设置cookie的获取范围。默认情况下,设置当前的虚拟目录
       * 如果要共享,则可以将path设置为"/"
    
    1. 不同的tomcat服务器间cookie共享问题?
      • setDomain(String path):如果设置一级域名相同,那么多个服务器之间cookie可以共享
      • setDomain(".baidu.com"),那么tieba.baidu.com和news.baidu.com中cookie可以共享

5.Cookie的特点

  1. cookie存储数据在客户端浏览器
  2. 浏览器对于单个cookie 的大小有限制(4kb) 以及 对同一个域名下的总cookie数量也有限制(20个)
  • 作用:
    1. cookie一般用于存出少量的不太敏感的数据
    2. 在不登录的情况下,完成服务器对客户端的身份识别

6.案例记录上一次登录的时间

@WebServlet(name = "Text", value = "/Text")
public class Text extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应的消息体的数据格式以及编码
        response.setContentType("text/html;charset=utf-8");
        //1.获取所有的Cookie
        Cookie[] cookies = request.getCookies();
        boolean flag = false;//没有cookie为lastTime
        //2.遍历cookie数组
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //3.获取cookie的名称
                String name = cookie.getName();
                //4.判断名称是否是lastTime
                if ("lastTime".equals(name)) {
                    //有该Cookie,不是第一次访问
                    flag = true;//有lastTime的cookie
                    //获取当前时间的字符串重新设置Cookie的值
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_data = sdf.format(date);
                    //url编码
                    str_data = URLEncoder.encode(str_data,"utf-8");
                    cookie.setValue(str_data);
                    //设置cookie的存活时间
                    cookie.setMaxAge(60 * 60 * 24);
                    response.addCookie(cookie);
                    //响应数据
                    String value = cookie.getValue();
                    //编码utf-8
                    value = URLDecoder.decode(value,"utf-8");
                    response.getWriter().write("<h1>欢迎回来,您上次访问时间为" + value + "<h1>");
                    break;
                }
            }
        }
        if(cookies == null || cookies.length == 0 || flag == false){
            //没有,第一次访问

            //设置Cookie的value
            //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
            Date date  = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            System.out.println("编码前:"+str_date);
            //URL编码
            str_date = URLEncoder.encode(str_date,"utf-8");
            System.out.println("编码后:"+str_date);

            Cookie cookie = new Cookie("lastTime",str_date);
            //设置cookie的存活时间
            cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
            response.addCookie(cookie);

            response.getWriter().write("<h1>您好,欢迎您首次访问</h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
2.session
  1. 概念:服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象中。HttpSession

  2. 快速入门

  3. 获取HttpSession对象:
    HttpSession session = request.getSession();

  4. 使用HttpSession对象:
    Object getAttribute(String name)
    void setAttribute(String name, Object value)
    void removeAttribute(String name)

```java
//获取HttpSession
HttpSession hs = request.getSession();
//设置session
hs.setAttribute("set","123");
System.out.println(hs);
```
  1. 获取HttpSession对象:

    //获取HttpSession
    HttpSession hs = request.getSession();
    Object ms = hs.getAttribute("set");
    System.out.println(ms);
    
  2. 保持Session会话:

       @Override
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取HttpSession
    HttpSession hs = request.getSession();
    //期望客户端关闭之后session也能相同
    Cookie c = new Cookie("JSESSIONID",hs.getId());
    //添加cookie,保持会话
    c.setMaxAge(60*60);
    response.addCookie(c);
    //设置session
    hs.setAttribute("set","123");System.out.println(hs);
    }
    
    
    
  3. 原理

  • Session的实现是依赖于Cookie的。
  1. 细节
  2. 当客户端关闭后,服务器不关闭,两次获取session是否为同一个?
* 默认情况下。不是。
* 如果需要相同,则可以创建Cookie,键为JSESSIONID,设置最大存活时间,让cookie持久化保存。
   Cookie c = new Cookie("JSESSIONID",session.getId());
       c.setMaxAge(60*60);
       response.addCookie(c);
  1. 客户端不关闭,服务器关闭后,两次获取的session是同一个吗?
* 不是同一个,但是要确保数据不丢失。tomcat自动完成以下工作
  * session的钝化:
    * 在服务器正常关闭之前,将session对象系列化到硬盘上
  * session的活化:
    * 在服务器启动后,将session文件转化为内存中的session对象即可。
  1. session什么时候被销毁?

  2. 服务器关闭

  3. session对象调用invalidate() 。

  4. session默认失效时间 30分钟
    选择性配置修改
    < s e s s i o n − c o n f i g > < s e s s i o n − t i m e o u t > 30 < / s e s s i o n − t i m e o u t > < / s e s s i o n − c o n f i g > <session-config> <session-timeout>30</session-timeout> </session-config> <sessionconfig><sessiontimeout>30</sessiontimeout></sessionconfig>

  5. session的特点

    1. session用于存储一次会话的多次请求的数据,存在服务器端
    2. session可以存储任意类型,任意大小的数据
    • session与Cookie的区别:
      1. session存储数据在服务器端,Cookie在客户端
      2. session没有数据大小限制,Cookie有
      3. session数据安全,Cookie相对于不安全

验证码案例

@WebServlet(name = "Demo05", value = "/rpdemo05")
public class CheckCode extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 50;

        //1.创建一对象,在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);


        //2.美化图片
        //2.1 填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.PINK);//设置画笔颜色
        g.fillRect(0,0,width,height);

        //2.2画边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width - 1,height - 1);

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        //生成随机角标
        Random ran = new Random();
        //新建一个输入流
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);//随机字符
            sb.append(ch);
            //2.3写验证码
            g.drawString(ch+"",width/5*i,height/2);
        }
        String checkCode_session = sb.toString();
        //将验证码存入session
        request.getSession().setAttribute("checkCode_session",checkCode_session);
        //2.4画干扰线
        g.setColor(Color.GREEN);

        //随机生成坐标点

        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }


        //3.将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
登录验证码案例
@WebServlet(value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置request编码
        request.setCharacterEncoding("utf-8");
        //2.获取参数Map
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");

        //3.先判断验证码是否正确
        //3.1获取验证码
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        //删除验证码
        session.removeAttribute("checkCode_session");
        //3.2判断验证码
        if (checkCode_session != null && checkCode_session.equalsIgnoreCase(checkCode)) {
            //忽略大小写
            //判断用户名和密码是否一致
            //验证码一直
            if ("lanlan".equals(username) && "123456".equals(password)) {
                //登录成功
                //存储用户信息
                session.setAttribute("user", username);
                //重定向
                response.sendRedirect(request.getContextPath() + "/success.jsp");
            } else {
                //验证不一致
                request.setAttribute("cc_error", "用户名或密码错误");
                //转发登录页面
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }

        } else {
            //验证码不一致
            request.setAttribute("cc_error", "验证码不一直");
            //转发登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值