前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用spring session解决session共享问题

使用spring session解决session共享问题

作者头像
栋先生
发布2018-09-29 16:46:16
4.7K0
发布2018-09-29 16:46:16
举报
文章被收录于专栏:Java成长之路Java成长之路

在Web项目中配置Spring Session分为四步:

  • 搭建用于Spring Session的数据存储
  • 将Spring Session的jar文件添加到web应用中
  • 将Spring Session filter添加到web应用的配置中
  • 配置Spring Session如何选择session数据存储的连接

一、导入Maven依赖

借助像Maven或Gradle这样的依赖管理器,将Spring Session添加应用中是很容易的。

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>1.3.0.RELEASE</version>
    <type>pom</type>
</dependency>
<dependency>
    <groupId>biz.paluch.redis</groupId>
    <artifactId>lettuce</artifactId>
    <version>3.5.0.Final</version>
</dependency>

二、 添加Spring配置文件

进行配置前,需要先安装redis,然后基于redis进行一系列的配置。Linux下的redis安装教程:Linux下redis安装和部署 ,windows下直接官网下载,运行即可。 添加了必要的依赖之后,我们需要创建相应的Spring配置。Spring配置是要创建一个Servlet过滤器,它用Spring Session支持的HttpSession实现来替换容器本身HttpSession实现。这一步也是Spring Session的核心。(注意:需添加对应的xml声明文件)

代码语言:javascript
复制
    <!-- 创建名为 springSessionRepositoryFilter 的Spring Bean,继承自Filter。
        springSessionRepositoryFilter替换容器默认的HttpSession支持为Spring Session,
        将Session实例存放在Redis中 -->
    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
    <!-- 使用LettuceConnectionFactory -->
    <bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory">
        <property name="hostName" value="127.0.0.1"/>
        <property name="port" value="6379"/>
    </bean>
    <!-- 让Spring Session不再执行config命令 -->
    <util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>

三、在web.xml中添加相应的filter过滤器

在web.xml中加入以下过滤器,注意如果web.xml中有其他过滤器,一般情况下Spring Session的过滤器要放在第一位

代码语言:javascript
复制
<filter>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

参考文章: 使用Spring Session和Redis解决分布式Session跨域共享问题

Spring session原理简介

Spring Session解决分布式Session问题的实现原理

初识 Spring Security

Spring Security3源码分析-FilterChainProxy初始化

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年03月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、导入Maven依赖
  • 二、 添加Spring配置文件
  • 三、在web.xml中添加相应的filter过滤器
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档