zoukankan      html  css  js  c++  java
  • Springboot使用session

    背景

    浏览器发起请求--> 服务端创建session,会话建立--> 服务端返回sessionId作为cookie存储在浏览器中;

    浏览器再次发起请求,并且带着cookie--> 服务端通过cookie认证,确认是刚才建立的会话。


    代码实现

    这里使用的注解因为是代理对象,所以不用担心单例的问题

        @Autowired
        HttpServletRequest httpServletRequest;
    
    package com.example.testsession.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    
    
    @RestController
    @RequestMapping("/session")
    public class SessionController {
    
        @Autowired
        HttpServletRequest httpServletRequest;
    
        /**
         * 创建会话,并给session添加值
         *
         * @return
         */
        @RequestMapping("/set")
        @ResponseBody
        public void set() {
            System.out.println("----初次会话----");
    //        获得session,如果没有,自动创建一个
            HttpSession mySession = httpServletRequest.getSession();
            String mySessionId = mySession.getId();
    
            mySession.setAttribute("abc", "123");
    
            System.out.println("mySessionId:" + mySessionId);
    
        }
    
        /**
         * 浏览器通过cookie和服务端进行第二次会话
         */
        @RequestMapping("/get")
        @ResponseBody
        public void get() {
            System.out.println("----二次会话----");
    //        获得session,如果没有,返回null
            HttpSession mySession = httpServletRequest.getSession(false);
            String myCookie = mySession.getId();
    
            String vCode = (String) mySession.getAttribute("abc");
    
            System.out.println("myCookie:" + myCookie);
            System.out.println("get-s:" + vCode);
        }
    
    
    }
    
    

    通过路径访问

    http://localhost:8080/session/set
    

    http://localhost:8080/session/get
    

  • 相关阅读:
    说一说Java的Unsafe类
    阿里云CentOS下安装jdk
    LeetCode 5
    五种方法实现Java的Singleton单例模式
    聊聊Java的final关键字
    LeetCode 4
    Java9都快发布了,Java8的十大新特性你了解多少呢?
    【Spring】mvc:annotation-driven 使用
    【gradle】【maven】gradle 转 maven pom.xml
    [GIT]比较不同分支的差异
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/14875594.html
Copyright © 2011-2022 走看看