java spring session如何自定义cookie密钥

时间:2016-09-07 10:32:03

标签: spring session cookies redis

我使用spring session HttpSession,我如何自定义Cookie密钥,我尝试了这个解决方案:Custom cookie name when using Spring Session。但它不起作用,名字仍然是SESSION。

我的配置如下:

<context:annotation-config/>
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<context:property-placeholder location="classpath:/env/env_test.properties"/> 
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
     p:port="${spring.redis.port}" p:hostName="${spring.redis.host}"/>
<bean id="mapSessionRepository" class="org.springframework.session.MapSessionRepository" />
<bean id="sessionRepositoryFilter"             
  class="org.springframework.session.web.http.SessionRepositoryFilter">
  <constructor-arg ref="sessionRepository"/>
  <property name="httpSessionStrategy">
    <bean class="org.springframework.session.web.http.CookieHttpSessionStrategy">
      <property name="cookieName" value="_session_id" />
    </bean>
  </property>
</bean>

2 个答案:

答案 0 :(得分:0)

您只需添加以下bean即可创建custom cookie

    <bean class ="org.springframework.session.web.http.DefaultCookieSerializer">
            <property name="cookieName" value="JSESIONID"></property>       
    </bean>

JESSIONID - Custom Cookie Name

    Please remove below configuration fr`enter code here`om xml file.

    <bean id="sessionRepositoryFilter"             
      class="org.springframework.session.web.http.SessionRepositoryFilter">
      <constructor-arg ref="sessionRepository"/>
      <property name="httpSessionStrategy">
        <bean class="org.springframework.session.web.http.CookieHttpSessionStrategy">
          <property name="cookieName" value="_session_id" />
        </bean>
      </property>
    </bean>

答案 1 :(得分:0)

您必须使用类

创建一个bean。
org.springframework.session.web.http.DefaultCookieSerializer

因此,在将该bean声明为以下属性之后,您可以在该bean内部定义自定义属性:

org.springframework.session.web.http.CookieHttpSessionStrategy

例如:

<bean id="yourCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer">
        <property name="cookieName" value="yourCustomName"/>
        <property name="cookiePath" value="yourCustomPath"/>
        ...
</bean>
<bean id="cookieHttpSessionStrategy" class="org.springframework.session.web.http.CookieHttpSessionStrategy">
        <property name="cookieSerializer" ref="yourCookieSerializer"></property>
</bean>