### Run the sample with Gradle bootRun Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-findbyusername.adoc Run the Spring Session sample application for the find-by-username guide. Requires Redis 2.8+ installed on localhost with the default port (6379), or update the RedisConnectionFactory to point to another Redis server. After startup, the application is accessible at http://localhost:8080/. ```bash $ ./gradlew :spring-session-sample-boot-findbyusername:bootRun ``` -------------------------------- ### Run the httpsession-jdbc-xml sample with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-jdbc.adoc Run the sample application using Gradle. The command starts the Tomcat server for the httpsession-jdbc-xml sample. ```shell $ ./gradlew :spring-session-sample-xml-jdbc:tomcatRun ``` -------------------------------- ### Run the REST sample with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Starts the sample application using Gradle. Requires Redis 2.8+ running on localhost with the default port (6379). ```bash $ ./gradlew :spring-session-sample-javaconfig-rest:tomcatRun ``` -------------------------------- ### Instantiate RedisSessionRepository Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows a typical example of instantiating a RedisSessionRepository. Uses RedisOperations from Spring Data. Does not support publishing of session events. ```java include::{indexdoc-tests}[tags=new-redissessionrepository] ``` -------------------------------- ### Run httpsession-jdbc sample with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc Runs the httpsession-jdbc sample application using Gradle. After starting, access the app at http://localhost:8080/. ```shell $ ./gradlew :spring-session-sample-javaconfig-jdbc:tomcatRun ``` -------------------------------- ### Install Spring Session jars to local Maven cache Source: https://github.com/spring-projects/spring-session/blob/main/README.adoc Installs all spring-* jars into the local Maven cache. Use this after cloning to make the project artifacts available for local development. ```bash ./gradlew install ``` -------------------------------- ### Announce release on Slack Source: https://github.com/spring-projects/spring-session/blob/main/RELEASE.adoc Example message for announcing the release on Slack, including the keyword 'spring-session-announcing'. ```text spring-session-announcing 3.2.0 is available. ``` -------------------------------- ### Create a new RedisIndexedSessionRepository instance Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows a typical example of creating a new RedisIndexedSessionRepository instance. The code is included from the documentation test sources and is not shown inline. ```java include::{indexdoc-tests}[tags=new-redisindexedsessionrepository] ``` -------------------------------- ### Run the custom-cookie sample application with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-custom-cookie.adoc This command runs the sample application for the custom-cookie sample. Execute `$ ./gradlew :spring-session-sample-javaconfig-custom-cookie:tomcatRun` at the root of the source code to start the sample on Tomcat. ```shell $ ./gradlew :spring-session-sample-javaconfig-custom-cookie:tomcatRun ``` -------------------------------- ### Customize transaction operations for Spring Session JDBC Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Starts a configuration class that customizes transaction handling for Spring Session JDBC. The snippet shows the imports and class declaration, but the actual TransactionOperations bean definition is not shown in the source. This example is incomplete and is provided as a starting point for disabling transactions. ```java import org.springframework.transaction.support.TransactionOperations; @Configuration @EnableJdbcHttpSession public class SessionConfig { ``` -------------------------------- ### Clone Spring Session repository Source: https://github.com/spring-projects/spring-session/blob/main/README.adoc Clones the Spring Session source repository from GitHub. Run this from the root of the source tree to start working with the codebase. ```bash git clone git@github.com:spring-projects/spring-session.git ``` -------------------------------- ### Redis HMSET command for saving a session Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows how each session is stored in Redis as a Hash using the HMSET command. The example includes the session ID, creation time, max inactive interval, last accessed time, and two session attributes. ```redis HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \ maxInactiveInterval 1800 \ lastAccessedTime 1404360000000 \ sessionAttr:attrName someAttrValue \ sessionAttr:attrName2 someAttrValue2 ``` -------------------------------- ### SpringSessionWebSession delegating to Spring Session's Session Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/web-session.adoc Custom WebSession implementation that wraps Session from Spring Session. It maintains a state (NEW, STARTED), delegates start(), isStarted(), and changeSessionId() operations, and delegates other methods to the underlying Session. This is for understanding the integration; you do not need to implement this logic manually. ```java public class SpringSessionWebSession implements WebSession { enum State { NEW, STARTED } private final S session; private AtomicReference state = new AtomicReference<>(); SpringSessionWebSession(S session, State state) { this.session = session; this.state.set(state); } @Override public void start() { this.state.compareAndSet(State.NEW, State.STARTED); } @Override public boolean isStarted() { State value = this.state.get(); return (State.STARTED.equals(value) || (State.NEW.equals(value) && !this.session.getAttributes().isEmpty())); } @Override public Mono changeSessionId() { return Mono.defer(() -> { this.session.changeSessionId(); return save(); }); } // ... other methods delegate to the original Session } ``` -------------------------------- ### Create Spring XML Configuration for Redis-backed HttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc This XML configuration defines the Spring beans to replace HttpSession with a Redis-backed implementation. Uses annotation-config and RedisHttpSessionConfiguration to create springSessionRepositoryFilter, and configures RedisConnectionFactory to connect to localhost on port 6379. Required for the quick start. ```XML include::{samples-dir}spring-session-sample-xml-redis/src/main/webapp/WEB-INF/spring/session.xml[tags=beans] ``` -------------------------------- ### SecurityInitializer class for loading Spring configuration Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc This is the SecurityInitializer class that loads the Spring configuration. It is used to add the Spring Session configuration to the existing Spring Security setup. ```java include::{samples-dir}spring-session-sample-javaconfig-security/src/main/java/sample/SecurityInitializer.java[tags=class] ``` -------------------------------- ### Expose DefaultCookieSerializer bean to customize the session cookie Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-custom-cookie.adoc Use Spring's @Bean and @Autowired annotations to customize the cookie. The DefaultCookieSerializer bean should set cookieName to 'JSESSIONID', cookiePath to '/', and domainNamePattern to '^.+?\.(\w+\.[a-z]+)$' with a comment. The example is highlighted with callouts numbered <1>, <2>, and <3>. No need to modify the code; the example is directly pulled from the source with the exact comments included. ```java @Bean public CookieSerializer cookieSerializer() { return new DefaultCookieSerializer() { @Autowired public void setCookieName() { } }; } ``` -------------------------------- ### Delete all Redis sessions with redis-cli Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc Delete all Redis keys to remove the session. This command is useful for clearing all sessions at once. Requires redis-cli installed. ```bash $ redis-cli keys '*' | xargs redis-cli del ``` -------------------------------- ### Set session timeout to 1 minute in application.properties Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-websocket.adoc Configuration property to set session timeout to 1 minute for testing expiration. The default is 30 minutes. Add this to src/main/resources/application.properties before starting the application. ```properties server.servlet.session.timeout=1m # Session timeout. If a duration suffix is not specified, seconds will be used. ``` -------------------------------- ### Set SessionIdGenerator directly on RedisSessionRepository Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/common.adoc When manually configuring a SessionRepository (instead of using @EnableRedisHttpSession), set the SessionIdGenerator directly on the repository implementation. This example uses RedisSessionRepository and requires a MySessionIdGenerator bean. ```java @Bean public RedisSessionRepository redisSessionRepository(RedisOperations redisOperations) { RedisSessionRepository repository = new RedisSessionRepository(redisOperations) repository.setSessionIdGenerator(new MySessionIdGenerator()); return repository; } ``` -------------------------------- ### Disable automatic Redis Keyspace events with ConfigureRedisAction.NO_OP (XML) Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc XML configuration example that adds ConfigureRedisAction.NO_OP as a bean to disable automatic Redis Keyspace event configuration in secured Redis environments where the config command is disabled. ```xml include::{docs-test-resources-dir}docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests-context.xml[tags=configure-redis-action] ``` -------------------------------- ### Disable automatic Redis Keyspace events with ConfigureRedisAction.NO_OP (Java) Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Java configuration example that adds ConfigureRedisAction.NO_OP as a bean to disable automatic Redis Keyspace event configuration in secured Redis environments where the config command is disabled. ```java include::{docs-test-dir}docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java[tags=configure-redis-action] ``` -------------------------------- ### Customize WebFlux session cookie with CookieWebSessionIdResolver Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-webflux-custom-cookie.adoc Expose a WebSessionIdResolver bean to customize the session cookie. The example sets the cookie name to JSESSIONID, the path to '/', and the SameSite directive to Strict. This augments existing Spring Session configuration when using annotations like @EnableRedisHttpSession. ```java include::{samples-dir}spring-session-sample-boot-webflux-custom-cookie/src/main/java/sample/CookieConfig.java[tags=webflux-cookie-serializer] ``` -------------------------------- ### Custom SessionIdGenerator bean Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/common.adoc Expose a custom SessionIdGenerator bean to override the default UuidSessionIdGenerator. The generate() method must return a String session id; the example shows a placeholder implementation. ```java @Bean public SessionIdGenerator sessionIdGenerator() { return new MySessionIdGenerator(); } class MySessionIdGenerator implements SessionIdGenerator { @Override public String generate() { // ... } } ``` -------------------------------- ### Run the sample application with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-jdbc.adoc Run the httpsession-jdbc-boot sample application using the Gradle bootRun task. After running, access the application at http://localhost:8080/. ```bash $ ./gradlew :spring-session-sample-boot-jdbc:bootRun ``` -------------------------------- ### Run the httpsession Sample Application Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-redis.adoc Run the sample application using Gradle with the tomcatRun task. ```bash $ ./gradlew :spring-session-sample-javaconfig-redis:tomcatRun ``` -------------------------------- ### Run the webflux-custom-cookie sample application Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-webflux-custom-cookie.adoc Command to run the sample application using Gradle. Requires Redis 2.8+ running on localhost with default port 6379. ```bash $ ./gradlew :spring-session-sample-boot-webflux-custom-cookie:bootRun ``` -------------------------------- ### Run the httpsession-xml sample application with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc Command to run the sample application using Gradle's tomcatRun task. Requires Redis 2.8+ running on localhost with default port 6379. ```bash $ ./gradlew :spring-session-sample-xml-redis:tomcatRun ``` -------------------------------- ### Run security sample with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc Run the security sample application using Gradle. Requires Redis 2.8+ running on localhost with default port 6379, or update the RedisConnectionFactory to point to another server. ```bash $ ./gradlew :spring-session-sample-javaconfig-security:tomcatRun ``` -------------------------------- ### Run the Boot sample application with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc Run the Spring Session Boot Redis sample application using the Gradle bootRun task. Requires Redis 2.8+ running on localhost with default port 6379. ```bash $ ./gradlew :spring-session-sample-boot-redis:bootRun ``` -------------------------------- ### Run websocket sample application with Gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-websocket.adoc Command to run the websocket sample application using Gradle. The sample requires Redis 2.8+ on localhost with default port 6379. ```bash $ ./gradlew :spring-session-sample-boot-websocket:bootRun ``` -------------------------------- ### Build Spring Session project Source: https://github.com/spring-projects/spring-session/blob/main/README.adoc Compiles and tests the project, building all jars, distribution zips, and documentation. This is the standard build command for Spring Session. ```bash ./gradlew build ``` -------------------------------- ### Run all checks with ./gradlew check Source: https://github.com/spring-projects/spring-session/blob/main/RELEASE.adoc Runs the full build and checks. Used in steps 1 and 4 to verify the project builds and passes all checks. ```bash $ ./gradlew check ``` -------------------------------- ### Configure Web.xml Context Param and Listener Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc The web.xml configuration loads the session.xml configuration via context-param and adds the ContextLoaderListener to read it. This is part of XML servlet container initialization. ```XML include::{samples-dir}spring-session-sample-xml-redis/src/main/webapp/WEB-INF/web.xml[tags=context-param] include::{samples-dir}spring-session-sample-xml-redis/src/main/webapp/WEB-INF/web.xml[tags=listeners] ``` -------------------------------- ### Tag the release and push the tag Source: https://github.com/spring-projects/spring-session/blob/main/RELEASE.adoc Creates a git tag for the release version and pushes it to the remote repository. ```bash git tag 3.0.0-RC1 git push origin 3.0.0-RC1 ``` -------------------------------- ### Instantiate MapSessionRepository (include directive) Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Placeholder for the code that instantiates a new MapSessionRepository. The actual code is included from the test sources via an AsciiDoc include directive. ```java include::{indexdoc-tests}[tags=new-mapsessionrepository] ``` -------------------------------- ### Copy release notes to clipboard with xclip Source: https://github.com/spring-projects/spring-session/blob/main/RELEASE.adoc Copies the generated release notes file to the clipboard using xclip. The command may vary depending on the system. ```bash cat release-notes | xclip -selection clipboard ``` -------------------------------- ### Authenticate with basic credentials Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Authenticates with basic credentials and receives a response containing an X-Auth-Token header with a new session ID. ```bash $ curl -v http://localhost:8080/ -u user:password ``` -------------------------------- ### Instantiate JdbcIndexedSessionRepository (include directive) Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Placeholder for the code that creates a new JdbcIndexedSessionRepository instance. The actual code is included from the test sources via an AsciiDoc include directive. ```java include::{indexdoc-tests}[tags=new-jdbcindexedsessionrepository] ``` -------------------------------- ### Add spring-boot-starter-session-data-redis dependency in pom.xml Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc Add the Spring Boot starter for Spring Session with Redis to your Maven pom.xml. Spring Boot manages the dependency version, so no explicit version is needed. ```xml org.springframework.boot spring-boot-starter-session-data-redis ``` -------------------------------- ### Request the application without authentication Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Sends an initial request to the application. The user is prompted for basic authentication with username 'user' and password 'password'. ```bash $ curl -v http://localhost:8080/ ``` -------------------------------- ### Initialize SockJS and STOMP client for chat Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-samples/spring-session-sample-boot-websocket/src/main/resources/templates/index.html Initializes a SockJS connection to '/messages', wraps it with Stomp, creates an ApplicationModel, applies Knockout bindings, and connects. This script is embedded in the chat page to set up WebSocket messaging. ```javascript (function() { var socket = new SockJS('/messages'); var stompClient = Stomp.over(socket); var appModel = new ApplicationModel(stompClient); ko.applyBindings(appModel); appModel.connect(); })(); ``` -------------------------------- ### Include SessionServlet class from sample Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc Includes the SessionServlet class from the sample source. The actual code is not shown on this page; it is referenced via an include directive. ```java include::{samples-dir}spring-session-sample-javaconfig-jdbc/src/main/java/sample/SessionServlet.java[tags=class] ``` -------------------------------- ### Add spring-boot-starter-session-data-redis dependency in build.gradle Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc Add the Spring Boot starter for Spring Session with Redis to your Gradle build. Spring Boot manages the dependency version, so no explicit version is needed. ```groovy implementation("org.springframework.boot:spring-boot-starter-session-data-redis") ``` -------------------------------- ### Response with new session Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Response after creating a new session: HTTP 200, a new X-Auth-Token, and the username. ```http HTTP/1.1 200 OK ... X-Auth-Token: 7e8383a4-082c-4ffe-a4bc-c40fd3363c5e {"username":"user"} ``` -------------------------------- ### Servlet container initialization with AbstractHttpSessionApplicationInitializer Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc The Initializer class extends AbstractHttpSessionApplicationInitializer to register the springSessionRepositoryFilter and load the Spring configuration. ```java include::{samples-dir}spring-session-sample-javaconfig-jdbc/src/main/java/sample/Initializer.java[tags=class] ``` -------------------------------- ### web.xml context-param and listeners for Spring Session Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-jdbc.adoc This web.xml configuration loads the session.xml configuration via the context-param and registers the ContextLoaderListener. The listener reads the contextConfigLocation and picks up the session.xml configuration. ```xml include::{samples-dir}spring-session-sample-xml-jdbc/src/main/webapp/WEB-INF/web.xml[tags=context-param] include::{samples-dir}spring-session-sample-xml-jdbc/src/main/webapp/WEB-INF/web.xml[tags=listeners] ``` -------------------------------- ### Java Servlet Container Initialization with AbstractHttpSessionApplicationInitializer Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-redis.adoc Extend AbstractHttpSessionApplicationInitializer to register the springSessionRepositoryFilter for every request and ensure Spring loads the Config class. The class name does not matter. ```java include::{samples-dir}spring-session-sample-javaconfig-redis/src/main/java/sample/Initializer.java[tags=class] ``` -------------------------------- ### Redis commands for creating a new session Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows the Redis commands executed when creating a new session. It uses HMSET to store session attributes, EXPIRE to set timeouts, APPEND to create an expiration marker, and SADD to add the session to an expiration set. ```redis HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \ maxInactiveInterval 1800 \ lastAccessedTime 1404360000000 \ sessionAttr:attrName someAttrValue \ sessionAttr:attrName2 someAttrValue2 EXPIRE spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe 2100 APPEND spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe "" EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800 SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe EXPIRE spring:session:expirations1439245080000 2100 ``` -------------------------------- ### Spring Configuration for WebSocket with Spring Session Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-websocket.adoc The first block shows a typical WebSocketMessageBrokerConfigurer implementation. The second block shows the updated configuration that extends AbstractSessionWebSocketMessageBrokerConfigurer and renames registerStompEndpoints to configureStompEndpoints. Both are included from external files and are shown as the before and after configuration. ```java include::{websocketdoc-test-dir}WebSocketConfig.java[tags=class] ``` ```java include::{samples-dir}spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketConfig.java[tags=class] ``` -------------------------------- ### View session keys in Redis with redis-cli keys * Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows how to inspect session keys in Redis using redis-cli. The first key is the session identifier, the second key contains session IDs to be deleted at the expiration time. ```bash $ redis-cli redis 127.0.0.1:6379> keys * 1) "spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021" <1> 2) "spring:session:expirations:1418772300000" <2> ``` -------------------------------- ### Initializer extending AbstractHttpSessionApplicationInitializer Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Initializer class that extends AbstractHttpSessionApplicationInitializer with the default constructor. The class name does not matter; extending the abstract class is what registers the filter. ```java include::{samples-dir}spring-session-sample-javaconfig-rest/src/main/java/sample/Initializer.java[tags=class] ``` -------------------------------- ### MvcInitializer for Spring Session Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Servlet container initializer that loads the Spring configuration class. Extend AbstractHttpSessionApplicationInitializer to register the springSessionRepositoryFilter for every request. ```java include::{samples-dir}spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcInitializer.java[tags=config] ``` -------------------------------- ### Enable Redis Indexed Web Sessions with @EnableRedisIndexedWebSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/reactive-redis-indexed.adoc Enable reactive Redis Indexed Web Session support by adding the @EnableRedisIndexedWebSession annotation to a configuration class. After this, your application has reactive Redis backed Indexed Web Session support. ```java @Configuration @EnableRedisIndexedWebSession public class SessionConfig { // ... } ``` -------------------------------- ### Add spring-session-data-redis dependency (Maven/Gradle) Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/reactive-redis-indexed.adoc Add the spring-session-data-redis dependency to your project to enable Redis Indexed Web Session support. The Maven and Gradle variants are shown as equivalent options. ```xml org.springframework.session spring-session-data-redis ``` ```groovy implementation 'org.springframework.session:spring-session-data-redis' ``` -------------------------------- ### Spring configuration for Redis-backed HttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Spring configuration that creates a servlet filter to replace the HttpSession with a Redis-backed implementation. The @EnableRedisHttpSession annotation creates the springSessionRepositoryFilter bean, and a RedisConnectionFactory connects to localhost on port 6379. HTTP headers are used to convey session information instead of cookies. ```java include::{samples-dir}spring-session-sample-javaconfig-rest/src/main/java/sample/HttpSessionConfig.java[tags=class] ``` -------------------------------- ### Generate release notes with github-changelog-generator Source: https://github.com/spring-projects/spring-session/blob/main/RELEASE.adoc Generates release notes using the GitHub changelog generator. The $MILESTONE variable should be replaced with the release version (e.g., 3.0.4 or 3.0.0-M1). Creates a file named 'release-notes'. ```bash java -jar github-changelog-generator.jar \ --changelog.repository=spring-projects/spring-session \ $MILESTONE release-notes ``` -------------------------------- ### Spring Java Configuration for Redis-backed HttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-redis.adoc Create a Spring configuration class that uses @EnableRedisHttpSession to replace the HttpSession with a Redis-backed implementation. The annotation creates a bean named springSessionRepositoryFilter. Also configure a RedisConnectionFactory to connect to Redis on localhost:6379. ```java include::{samples-dir}spring-session-sample-javaconfig-redis/src/main/java/sample/Config.java[tags=class] ``` -------------------------------- ### Response after authentication Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Shows the response after authenticating: HTTP 200, an X-Auth-Token header containing a new session ID, and the current username. ```http HTTP/1.1 200 OK ... X-Auth-Token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3 {"username":"user"} ``` -------------------------------- ### Enable Spring HTTP session with @EnableSpringHttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows a configuration class using @EnableSpringHttpSession to expose SessionRepositoryFilter as a bean named springSessionRepositoryFilter. Requires a single SessionRepository bean. No infrastructure for session expiration is configured. ```java include::{docs-test-dir}docs/SpringHttpSessionConfig.java[tags=class] ``` -------------------------------- ### Enable Spring Session JDBC with @EnableJdbcHttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Enable Spring Session JDBC in a non-Spring Boot application by adding @EnableJdbcHttpSession to a configuration class. This is required only when Spring Boot is not used. ```java @Configuration @EnableJdbcHttpSession public class SessionConfig { //... } ``` -------------------------------- ### CookieSerializer configuration include directive Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc This is an AsciiDoc include directive that pulls in a Java code snippet from the sample project. It is not actual Java code but a reference to an external file. The directive is used to embed the custom CookieSerializer configuration in the documentation. ```java include::{samples-dir}spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Config.java[tags=cookie-serializer] ``` -------------------------------- ### Create PostgreSQL tables with JSONB attribute column Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Creates the SPRING_SESSION and SPRING_SESSION_ATTRIBUTES tables with a JSONB column for ATTRIBUTE_BYTES, required for storing session attributes as JSON in PostgreSQL. ```sql CREATE TABLE SPRING_SESSION ( -- ... ); -- indexes... CREATE TABLE SPRING_SESSION_ATTRIBUTES ( -- ... ATTRIBUTE_BYTES JSONB NOT NULL, -- ... ); ``` -------------------------------- ### Initializer class extending AbstractHttpSessionApplicationInitializer Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc This is the Initializer class that extends AbstractHttpSessionApplicationInitializer. It ensures the springSessionRepositoryFilter is registered before Spring Security's springSecurityFilterChain, so the HttpSession is backed by Spring Session. ```java include::{samples-dir}spring-session-sample-javaconfig-security/src/main/java/sample/Initializer.java[tags=class] ``` -------------------------------- ### View session keys in Redis with redis-cli Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows how to inspect session keys in Redis using redis-cli. The key suffix is the session identifier of the Spring Session. ```bash $ redis-cli redis 127.0.0.1:6379> keys * 1) "spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021" ``` -------------------------------- ### Inspect Redis session hash with hkeys and hget Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows Redis CLI commands to inspect a session hash stored by Spring Session. The hkeys command lists the hash fields, and hget retrieves a specific attribute value, which is serialized with Java serialization (shown as escaped bytes). ```bash redis 127.0.0.1:6379> hkeys spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 1) "lastAccessedTime" 2) "creationTime" 3) "maxInactiveInterval" 4) "sessionAttr:username" redis 127.0.0.1:6379> hget spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 sessionAttr:username "\xac\xed\x00\x05t\x00\x03rob" ``` -------------------------------- ### PostgreSQL schema script for Spring Session JDBC Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Use the PostgreSQL schema script provided by Spring Session JDBC. The script is packaged as org/springframework/session/jdbc/schema-postgresql.sql and should be used with PostgreSQL. Scripts for other database vendors are available as schema-*.sql. ```sql include::{session-jdbc-main-resources-dir}org/springframework/session/jdbc/schema-postgresql.sql[] ``` -------------------------------- ### Enable Spring Web session with @EnableSpringWebSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows a configuration class using @EnableSpringWebSession to expose WebSessionManager as a bean named webSessionManager. Requires a single ReactiveSessionRepository bean. No infrastructure for session expiration is configured; you are responsible for cleaning up expired sessions. ```java include::{docs-test-dir}docs/SpringWebSessionConfig.java[tags=class] ``` -------------------------------- ### Spring configuration for Redis-backed HttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc This is the Spring configuration class that enables Redis-backed HttpSession support. The @EnableRedisHttpSession annotation creates the springSessionRepositoryFilter bean, and the RedisConnectionFactory connects to Redis on localhost:6379. ```java include::{samples-dir}spring-session-sample-javaconfig-security/src/main/java/sample/Config.java[tags=class] ``` -------------------------------- ### Create and expire a session expires key Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Creates a separate expires key for the session. The APPEND command creates the key and the EXPIRE sets its TTL to 1800 seconds (30 minutes). This key is used to trigger expiration events. ```redis APPEND spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe "" EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800 ``` -------------------------------- ### Enable Redis Keyspace events with redis-cli config set notify-keyspace-events Egx Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Enables Redis Keyspace events for Generic commands and Expired events, which are required for firing SessionDeletedEvent or SessionExpiredEvent through the SessionMessageListener. Run this in redis-cli when not using automatic configuration. ```bash redis-cli config set notify-keyspace-events Egx ``` -------------------------------- ### MySQL schema include directive Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc This is an AsciiDoc include directive that pulls in the MySQL schema for Spring Session JDBC. It is not actual SQL code but a reference to an external file. The directive is used to embed the schema in the documentation. ```sql include::{session-jdbc-main-resources-dir}org/springframework/session/jdbc/schema-mysql.sql[] ``` -------------------------------- ### @EnableRedisWebSession configuration for WebSession with Redis Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/web-session.adoc Add this @Configuration class to enable Redis-backed WebSession support. The @EnableRedisWebSession annotation registers a bean named webSessionManager implementing WebSessionManager. The LettuceConnectionFactory bean connects to Redis on localhost port 6379 by default. ```java @EnableRedisWebSession // <1> public class SessionConfiguration { @Bean public LettuceConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(); // <2> } } ``` -------------------------------- ### Listen to session events with @EventListener Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Listens to session lifecycle events (SessionCreatedEvent, SessionDeletedEvent, SessionDestroyedEvent, SessionExpiredEvent) using @EventListener. Requires the indexed repository to be configured. ```java @Component public class SessionEventListener { @EventListener public void processSessionCreatedEvent(SessionCreatedEvent event) { // do the necessary work } @EventListener public void processSessionDeletedEvent(SessionDeletedEvent event) { // do the necessary work } @EventListener public void processSessionDestroyedEvent(SessionDestroyedEvent event) { // do the necessary work } @EventListener public void processSessionExpiredEvent(SessionExpiredEvent event) { // do the necessary work } } ``` -------------------------------- ### Enable RedisSessionRepository with @EnableRedisHttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Enables the RedisSessionRepository using the @EnableRedisHttpSession annotation. Place this configuration class in your Spring application to use the default Redis-backed session repository. ```java @Configuration @EnableRedisHttpSession public class SessionConfig { // ... } ``` -------------------------------- ### Enable RedisIndexedSessionRepository with @EnableRedisIndexedHttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Enables the RedisIndexedSessionRepository using the @EnableRedisIndexedHttpSession annotation. This configuration is required to use the indexed repository, which supports session events and finding sessions by user. ```java @Configuration @EnableRedisIndexedHttpSession public class SessionConfig { // ... } ``` -------------------------------- ### Add Maven dependencies for Spring Session with Redis Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc Add the required Spring Session and Redis dependencies to your Maven pom.xml. The spring-session-data-redis dependency provides the Redis-backed session repository, lettuce-core is the Redis client, and spring-web is needed for the servlet integration. ```xml org.springframework.session spring-session-data-redis {spring-session-version} pom io.lettuce lettuce-core {lettuce-core-version} org.springframework spring-web {spring-core-version} ``` -------------------------------- ### Configure Redis connection properties in application.properties Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc Set the Redis server host, password, and port in application.properties for production environments. The default is localhost on port 6379. ```properties spring.data.redis.host=localhost # Redis server host. spring.data.redis.password= # Login password of the redis server. spring.data.redis.port=6379 # Redis server port. ``` -------------------------------- ### SessionServlet.java Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-redis.adoc The SessionServlet interacts with the standard HttpSession. This is the main servlet class for the sample application. ```java include::{samples-dir}spring-session-sample-javaconfig-redis/src/main/java/sample/SessionServlet.java[tags=class] ``` -------------------------------- ### Specify Redis namespace with spring.session.data.redis.namespace Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Sets the Redis namespace to 'spring:session:myapplication' using Spring Boot properties. The first block is the .properties file, the second is the .yml equivalent. ```properties spring.session.data.redis.namespace=spring:session:myapplication ``` ```yml spring: session: data: redis: namespace: "spring:session:myapplication" ``` -------------------------------- ### Configure Spring Session data source with @SpringSessionDataSource Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc Configures two data sources, annotating the first with @SpringSessionDataSource so Spring Session uses it. The second data source is a placeholder for other application data. Requires the H2 schema script from the Spring Session JDBC module. ```java @Bean @SpringSessionDataSource // <1> public EmbeddedDatabase firstDataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2).addScript("org/springframework/session/jdbc/schema-h2.sql").build(); } @Bean public HikariDataSource secondDataSource() { // ... } } ``` -------------------------------- ### Find session by username using FindByIndexNameSessionRepository Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Shows how to find a session by username after it has been indexed. The code is an include directive referencing a test file with the tag 'findby-username'. ```java include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=findby-username] ``` -------------------------------- ### Custom session cleanup task using ReactiveRedisOperations Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/reactive-redis-indexed.adoc Provides a custom cleanup strategy that queries the expiration sorted set for session ids that expired within the last minute, using a limit of 1000. The `@Scheduled` method returns a `Mono` and is intended to replace the default cleanup task after disabling it. ```java @Component public class SessionEvicter { private ReactiveRedisOperations redisOperations; @Scheduled public Mono cleanup() { Instant now = Instant.now(); Instant oneMinuteAgo = now.minus(Duration.ofMinutes(1)); Range range = Range.closed((double) oneMinuteAgo.toEpochMilli(), (double) now.toEpochMilli()); Limit limit = Limit.limit().count(1000); return this.redisOperations.opsForZSet().reverseRangeByScore("spring:session:sessions:expirations", range, limit) // do something with the session ids .then(); } } ``` -------------------------------- ### Reuse session with X-Auth-Token Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Uses the X-Auth-Token header to make a request without re-authenticating. The session ID is not returned in the response because the session is reused. ```bash $ curl -v http://localhost:8080/ -H "X-Auth-Token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3" ``` -------------------------------- ### Find and remove user sessions Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Use these methods to find all sessions of a specific user and to remove a specific session of a user. The `getSessions` method returns a collection of sessions for the given principal, while `removeSession` deletes a session if it belongs to the user. ```java public Collection getSessions(Principal principal) { Collection usersSessions = this.sessions.findByPrincipalName(principal.getName()).values(); return usersSessions; } public void removeSession(Principal principal, String sessionIdToDelete) { Set usersSessionIds = this.sessions.findByPrincipalName(principal.getName()).keySet(); if (usersSessionIds.contains(sessionIdToDelete)) { this.sessions.deleteById(sessionIdToDelete); } } ``` -------------------------------- ### Customize delete-by-expiry-time query with SessionRepositoryCustomizer Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Customizes the delete-by-expiry-time query by defining a SessionRepositoryCustomizer bean that calls setDeleteSessionsByExpiryTimeQuery. The query uses %TABLE_NAME% as a placeholder for the table name. ```java @Configuration @EnableJdbcHttpSession public class SessionConfig { @Bean public SessionRepositoryCustomizer customizer() { return (sessionRepository) -> sessionRepository.setDeleteSessionsByExpiryTimeQuery(""" DELETE FROM %TABLE_NAME% WHERE EXPIRY_TIME < ? AND OTHER_COLUMN = 'value' """); } } ``` -------------------------------- ### Response after logout Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc Response after logout: HTTP 204 No Content and an empty X-Auth-Token header, indicating the session was invalidated. ```http HTTP/1.1 204 No Content ... X-Auth-Token: ``` -------------------------------- ### Configure DataSource properties in application.properties Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-jdbc.adoc Configure the DataSource for a production environment. Spring Boot automatically creates a DataSource for an embedded H2 database, but you need to update these properties to point to your relational database. ```properties spring.datasource.url= # JDBC URL of the database. spring.datasource.username= # Login username of the database. spring.datasource.password= # Login password of the database. ``` -------------------------------- ### SpringSessionWebSessionStore delegating to ReactiveSessionRepository Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/web-session.adoc Custom WebSessionStore implementation that wraps the ReactiveSessionRepository and delegates session creation to it, producing custom WebSession implementations. It must be registered as a bean named webSessionManager to be detected by Spring WebFlux. ```java public class SpringSessionWebSessionStore implements WebSessionStore { private final ReactiveSessionRepository sessions; public SpringSessionWebSessionStore(ReactiveSessionRepository reactiveSessionRepository) { this.sessions = reactiveSessionRepository; } // ... } ``` -------------------------------- ### Inject FindByIndexNameSessionRepository to find sessions by user Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Injects the FindByIndexNameSessionRepository to retrieve all sessions of a specific user. Requires the indexed repository to be configured. ```java @Autowired public FindByIndexNameSessionRepository sessions; ``` -------------------------------- ### Configure RedisSerializer with GenericJackson2JsonRedisSerializer Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/reactive-redis-indexed.adoc Provide a RedisSerializer bean to customize session serialization using Jackson's GenericJackson2JsonRedisSerializer. The bean name must be springSessionDefaultRedisSerializer to be picked up by Spring Session; otherwise it won't be used. ```java @Bean public RedisSerializer springSessionDefaultRedisSerializer(ObjectMapper objectMapper) { return new GenericJackson2JsonRedisSerializer(objectMapper); } ``` -------------------------------- ### Spring configuration for JDBC HttpSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc The Spring configuration class that enables JDBC-backed HttpSession using @EnableJdbcHttpSession. It creates a springSessionRepositoryFilter bean and configures a DataSource and transaction manager. ```java include::{samples-dir}spring-session-sample-javaconfig-jdbc/src/main/java/sample/Config.java[tags=class] ``` -------------------------------- ### Add Spring Session JDBC dependency to pom.xml Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-jdbc.adoc Add the spring-boot-starter-session-jdbc dependency to your Maven pom.xml. Spring Boot provides dependency management for Spring Session modules, so you need not explicitly declare the dependency version. ```xml org.springframework.boot spring-boot-starter-session-jdbc ``` -------------------------------- ### Custom RedisSessionExpirationStore bean with SortedSetRedisSessionExpirationStore Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Provides a custom RedisSessionExpirationStore bean using SortedSetRedisSessionExpirationStore. The bean is picked up by Spring Session Data Redis configuration. It configures a RedisTemplate with string serializers and uses the default namespace for the expiration store. ```java import org.springframework.session.data.redis.SortedSetRedisSessionExpirationStore; @Configuration @EnableRedisIndexedHttpSession public class SessionConfig { @Bean public RedisSessionExpirationStore redisSessionExpirationStore(RedisConnectionFactory redisConnectionFactory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.afterPropertiesSet(); return new SortedSetRedisSessionExpirationStore(redisTemplate, RedisIndexedSessionRepository.DEFAULT_NAMESPACE); } } ``` -------------------------------- ### Customize JDBC session attribute queries for PostgreSQL jsonb Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Customizes the SQL queries used by Spring Session JDBC to insert and update session attributes so that bytea values are encoded to text and converted to jsonb using PostgreSQL's convert_from function. The snippet defines two query constants and registers a SessionRepositoryCustomizer bean that sets them on the JdbcIndexedSessionRepository. Requires a PostgreSQL database and the use of the @EnableJdbcHttpSession annotation. ```java @Configuration @EnableJdbcHttpSession public class SessionConfig { private static final String CREATE_SESSION_ATTRIBUTE_QUERY = """ INSERT INTO %TABLE_NAME%_ATTRIBUTES (SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) VALUES (?, ?, convert_from(?, 'UTF8')::jsonb) <1> """; private static final String UPDATE_SESSION_ATTRIBUTE_QUERY = """ UPDATE %TABLE_NAME%_ATTRIBUTES SET ATTRIBUTE_BYTES = convert_from(?, 'UTF8')::jsonb WHERE SESSION_PRIMARY_ID = ? AND ATTRIBUTE_NAME = ? """; @Bean SessionRepositoryCustomizer customizer() { return (sessionRepository) -> { sessionRepository.setCreateSessionAttributeQuery(CREATE_SESSION_ATTRIBUTE_QUERY); sessionRepository.setUpdateSessionAttributeQuery(UPDATE_SESSION_ATTRIBUTE_QUERY); }; } } ``` -------------------------------- ### Customize cleanup cron with @EnableJdbcHttpSession(cleanupCron) Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Sets the cleanupCron attribute in @EnableJdbcHttpSession to a cron expression that runs the expired-session clean-up job at the top of every hour. The default job runs every minute. ```java @Configuration @EnableJdbcHttpSession(cleanupCron = "0 0 * * * *") // top of every hour of every day public class SessionConfig { } ``` -------------------------------- ### Set Redis namespace via redisNamespace attribute on @EnableRedisHttpSession, @EnableRedisIndexedHttpSession, or @EnableRedisWebSession Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Sets the Redis namespace via the redisNamespace attribute on the @EnableRedisHttpSession, @EnableRedisIndexedHttpSession, or @EnableRedisWebSession annotations. Each block shows a different annotation variant. ```java @Configuration @EnableRedisHttpSession(redisNamespace = "spring:session:myapplication") public class SessionConfig { // ... } ``` ```java @Configuration @EnableRedisIndexedHttpSession(redisNamespace = "spring:session:myapplication") public class SessionConfig { // ... } ``` ```java @Configuration @EnableRedisWebSession(redisNamespace = "spring:session:myapplication") public class SessionConfig { // ... } ``` -------------------------------- ### Configure RedisSessionRepository with Spring Boot properties Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/redis.adoc Sets the Redis session repository type to 'default' in Spring Boot properties. Use this to explicitly configure the RedisSessionRepository when it is not the default or to override an existing configuration. ```properties spring.session.data.redis.repository-type=default ``` ```yml spring: session: data: redis: repository-type: default ``` -------------------------------- ### Customize Spring Session properties in application.properties Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-jdbc.adoc Customize Spring Session behavior using application.properties. The properties control session timeout, schema initialization, schema location, and table name. ```properties server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds are used. spring.session.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. spring.session.jdbc.table-name=SPRING_SESSION # Name of the database table used to store sessions. ``` -------------------------------- ### SessionRepositoryFilter doFilter pseudocode Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/http-session.adoc Servlet filter that wraps the incoming HttpServletRequest with SessionRepositoryRequestWrapper and passes it to the filter chain. Must be placed before anything that interacts with HttpSession. ```java public class SessionRepositoryFilter implements Filter { public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { HttpServletRequest httpRequest = (HttpServletRequest) request; SessionRepositoryRequestWrapper customRequest = new SessionRepositoryRequestWrapper(httpRequest); chain.doFilter(customRequest, response, chain); } // ... } ``` -------------------------------- ### Add Spring Session JDBC dependency (Gradle and Maven) Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Add the Spring Session JDBC dependency to your build. Use the Gradle snippet for Gradle projects and the Maven snippet for Maven projects. Spring Boot auto-configures Spring Session JDBC when this dependency is present. ```groovy implementation 'org.springframework.session:spring-session-jdbc' ``` ```xml org.springframework.session spring-session-jdbc ``` -------------------------------- ### Register springSessionRepositoryFilter in web.xml Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc Declares the springSessionRepositoryFilter in web.xml to ensure the servlet container uses it for every request, applying the Redis-backed HttpSession. ```XML include::{samples-dir}spring-session-sample-xml-redis/src/main/webapp/WEB-INF/web.xml[tags=springSessionRepositoryFilter] ``` -------------------------------- ### Configure Spring Session Redis properties in application.properties Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc Customize Spring Session Redis behavior using application.properties. The properties set the session timeout, flush mode, and namespace for Redis keys. ```properties server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds is used. spring.session.data.redis.flush-mode=on_save # Sessions flush mode. spring.session.data.redis.namespace=spring:session # Namespace for keys used to store sessions. ``` -------------------------------- ### SessionServlet.java source code Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc The SessionServlet class that interacts with the standard HttpSession. This is included from the sample application source. ```java include::{samples-dir}spring-session-sample-xml-redis/src/main/java/sample/SessionServlet.java[tags=class] ``` -------------------------------- ### Customize table name with SessionRepositoryCustomizer Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/configuration/jdbc.adoc Customize the table name by exposing a SessionRepositoryCustomizer bean. The customizer calls setTableName on the repository to change the table directly. This approach is an alternative to using the tableName attribute on @EnableJdbcHttpSession. ```java @Configuration @EnableJdbcHttpSession public class SessionConfig { @Bean public TableNameCustomizer tableNameCustomizer() { return new TableNameCustomizer(); } } public class TableNameCustomizer implements SessionRepositoryCustomizer { @Override public void customize(JdbcIndexedSessionRepository sessionRepository) { sessionRepository.setTableName("MY_TABLE_NAME"); } } ``` -------------------------------- ### Set session expiration with EXPIRE Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Sets the expiration for a session key. The expiration is set to five minutes after the session actually expires to allow access to the session data after expiration. ```redis EXPIRE spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe 2100 ``` -------------------------------- ### Spring XML configuration for Spring Session JDBC Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/guides/xml-jdbc.adoc This is the Spring XML configuration that creates the springSessionRepositoryFilter bean. It uses and JdbcHttpSessionConfiguration because Spring Session does not yet provide XML Namespace support. The filter replaces the HttpSession with a Spring Session backed implementation, using a dataSource and transactionManager. ```xml include::{samples-dir}spring-session-sample-xml-jdbc/src/main/webapp/WEB-INF/spring/session.xml[tags=beans] ``` -------------------------------- ### Track session expiration with SADD and EXPIRE Source: https://github.com/spring-projects/spring-session/blob/main/spring-session-docs/modules/ROOT/pages/api.adoc Tracks session expiration to the nearest minute. The SADD command adds the expires key to a set, and EXPIRE sets the TTL for that set. This allows a background task to access potentially expired sessions and trigger Redis expiration events. ```redis SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe EXPIRE spring:session:expirations1439245080000 2100 ```