spring-session-data-redis无效

时间:2016-02-19 02:09:32

标签: spring spring-mvc spring-security spring-session

我已尝试过官方参考Spring Session提供的示例。通过http://localhost:8080/login登录后,似乎会话数据仍然存储在内存中,没有redis交互(通过redis-cli monitor命令观察)。只有JSESSIONID存储在cookie中

以下设置:

的web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

spring.xml:

<context:annotation-config/>
<beans:bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<beans:bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
            p:hostName="192.168.1.230"
            p:port="6379"
/>

<security:authentication-manager>
    <security:authentication-provider>
        <security:user-service>
            <security:user name="root" password="123456" authorities="ROLE_ADMIN"/>
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>
<security:global-method-security secured-annotations="enabled"/>
<security:http auto-config="true">
    <security:intercept-url pattern="/ping" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login default-target-url="/ping"/>
    <security:csrf disabled="true"/>
</security:http>

<mvc:annotation-driven/>

<context:component-scan base-package="io.hbprotoss.demo.controller"/>

1 个答案:

答案 0 :(得分:5)

您需要声明会话存储库过滤器,如下所示:

<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>
</filter-mapping>

由于您使用的是spring安全性,请确保在安全过滤器之前声明了会话存储库过滤器(以及可能要访问该会话的任何其他过滤器,否则您最终可能会遇到两个会话一个由servlet容器提供,一个由spring会话提供。

更多细节可以在这里找到 https://docs.spring.io/spring-session/docs/current/reference/html5/#xml-servlet-container-initialization