对于最新的稳定版本,请使用 Spring Session 3.5.2! |
春季会话 - Spring Boot
本指南介绍如何使用 Spring Session 透明地利用关系数据库来支持 Web 应用程序的HttpSession
当您使用 Spring Boot 时。
您可以在 httpsession-jdbc-boot 示例应用程序中找到完整的指南。 |
更新依赖项
在使用 Spring Session 之前,您必须更新依赖项。 我们假设您正在使用一个有效的 Spring Boot Web 应用程序。 如果您使用 Maven,则必须添加以下依赖项:
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
</dependencies>
Spring Boot 为 Spring Session 模块提供了依赖管理,因此您无需显式声明依赖版本。
Spring Boot 配置
添加所需的依赖项后,我们可以创建 Spring Boot 配置。 得益于一流的自动配置支持,只需添加依赖项,Spring Boot 就会为我们设置由关系数据库支持的 Spring Session。
如果类路径上存在单个 Spring Session 模块,则 Spring Boot 会自动使用该 store 实现。 如果你有多个实现,则必须选择要用于存储会话的 StoreType,如上所示。
在后台,Spring Boot 应用的配置相当于手动添加@EnableJdbcHttpSession
注解。 这将创建一个名为springSessionRepositoryFilter
.该 bean 实现Filter
. 过滤器负责更换HttpSession
由 Spring Session 支持的实现。
您可以使用以下命令进一步自定义application.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.
有关更多信息,请参阅 Spring Boot 文档的 Spring Session 部分。
配置DataSource
Spring Boot 会自动创建一个DataSource
将 Spring Session 连接到 H2 数据库的嵌入式实例。
在生产环境中,您需要更新配置以指向关系数据库。
例如,您可以在 application.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.
有关更多信息,请参阅 Spring Boot 文档的配置数据源部分。
Servlet 容器初始化
我们的 Spring Boot 配置创建了一个名为springSessionRepositoryFilter
实现Filter
. 这springSessionRepositoryFilter
bean 负责将HttpSession
使用由 Spring Session 支持的自定义实现。
为了我们的Filter
为了发挥它的魔力,Spring 需要加载我们的Config
类。
最后,我们需要确保我们的 Servlet 容器(即 Tomcat)使用springSessionRepositoryFilter
对于每个请求。幸运的是,Spring Boot 为我们处理了这两个步骤。
httpsession-jdbc-boot
示例应用
httpsession-jdbc-boot 示例应用程序演示了如何使用 Spring Session 透明地利用 H2 数据库来支持 Web 应用程序的HttpSession
当您使用 Spring Boot 时。
运行httpsession-jdbc-boot
示例应用
您可以通过获取源代码并调用以下命令来运行示例:
$ ./gradlew :spring-session-sample-boot-jdbc:bootRun
您现在应该能够在 localhost:8080/ 访问该应用程序
探索安全示例应用程序
您现在可以尝试使用该应用程序。 为此,请输入以下内容进行登录:
-
用户名 user
-
密码密码
现在点击 登录 按钮。
您现在应该会看到一条消息,指示您已使用之前输入的用户登录。
用户的信息存储在 H2 数据库中,而不是 Tomcat 的数据库中HttpSession
实现。
它是如何工作的?
而不是使用 Tomcat 的HttpSession
,我们将值保留在 H2 数据库中。
Spring Session 将HttpSession
使用由关系数据库支持的实现。
当 Spring Security 的SecurityContextPersistenceFilter
保存SecurityContext
到HttpSession
,然后将其持久化到 H2 数据库中。
当新的HttpSession
创建时,Spring Session 会创建一个名为SESSION
在您的浏览器中。该 cookie 包含您的会话的 ID。
您可以查看 cookie(使用 Chrome 或 Firefox)。
您可以使用以下位置提供的 H2 Web 控制台删除会话:localhost:8080/h2-console/(使用jdbc:h2:mem:testdb
对于 JDBC URL)。
现在您可以访问 localhost:8080/ 的应用程序,并看到我们不再经过身份验证。