使用spring session解决session共享问题

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

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

一、导入Maven依赖

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

<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声明文件)

    <!-- 创建名为 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的过滤器要放在第一位

<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初始化

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值