java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot根据sessionId查询session

springboot根据sessionId查询session方式

作者:佛说"獨"

文章介绍了通过保存session和sessionId进行跨域问题的校验,提出创建保存session的类,建立监听器监听session的创建和销毁,并在启动类上添加注解@ServletComponentScan以扫描SessionListener

问题

跨域问题,session无法进行同步,可以通过保存session和sessionId的方式进行校验,向前端传送sessionId,前端可以通过头部传sessionId,通过sessionId获取相关的信息,进行校验等操作

1、创建一个类用于保存session

对session进行添加,删除,查询

/**
 * 自定义获取指定sessionId的session
 */
public class MySessionContext {
    private static MySessionContext instance;
    private HashMap mymap;

    private MySessionContext() {
        mymap = new HashMap();
    }

    /**
     * 创建MySessionContext的对象
     * @return
     */
    public static MySessionContext getInstance() {
        if (instance == null) {
            instance = new MySessionContext();
        }
        return instance;
    }

    /**
     * 添加session
     * @param session
     */
    public synchronized void AddSession(HttpSession session) {
        if (session != null) {
            mymap.put(session.getId(), session);
        }
    }

    /**
     * 删除session
     * @param session
     */
    public synchronized void DelSession(HttpSession session) {
        if (session != null) {
            mymap.remove(session.getId());
        }
    }

    /**
     * 查询session
     * @param session_id
     * @return
     */
    public synchronized HttpSession getSession(String session_id) {
        if (session_id == null) {
            return null;
        }
        return (HttpSession) mymap.get(session_id);
    }

}

2、建立一个监听器

监听session的创建和销毁

/**
 * 监听器来监控session的创建销毁
 */
@WebListener
public class SessionListener implements HttpSessionListener {

    private MySessionContext myc = MySessionContext.getInstance();

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        myc.AddSession(httpSessionEvent.getSession());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        myc.DelSession(session);
    }
}

3、在启动类上添加注解

@ServletComponentScan用于扫描到SessionListener

@SpringBootApplication
@ServletComponentScan
public class RunMain{
	public static void main(String[] args) {
		SpringApplication.run(RunMain.class, args);
	}	
}

操作代码

 //创建MySessionContext对象
 MySessionContext myContext = MySessionContext.getInstance();
 //存储session
 myContext.AddSession(session);
 //根据sessionId获取session
 HttpSession httpSession = myContext.getSession(sessionId);
 //删除session
 myContext.DelSession(session);

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文