Spring Session - HttpSession (Quick Start)

此指南将介绍如何使用 Spring Session 透明地利用关系数据库来使用 Java 配置来为 Web 应用程序的 HttpSession 提供支持。

This guide describes how to use Spring Session to transparently leverage a relational database to back a web application’s HttpSession with Java Configuration.

您可以在httpsession-jdbc sample application中找到已完成指南。

You can find the completed guide in the httpsession-jdbc-sample.

Updating Dependencies

在使用 Spring 会话之前,您必须更新依赖。如果您使用 Maven,您必须添加以下依赖:

Before you use Spring Session, you must update your dependencies. If you use Maven, you must add the following dependencies:

pom.xml
<dependencies>
	<!-- ... -->

	<dependency>
		<groupId>org.springframework.session</groupId>
		<artifactId>spring-session-jdbc</artifactId>
		<version>{spring-session-version}</version>
		<type>pom</type>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>{spring-core-version}</version>
	</dependency>
</dependencies>

Spring Java Configuration

添加所需的依赖项后,我们就可以创建我们的 Spring 配置。Spring 配置负责创建一个 Servlet 过滤器,它将 HttpSession 实现替换为由 Spring Session 支持的实现。为此,请添加以下 Spring 配置:

After adding the required dependencies, we can create our Spring configuration. The Spring configuration is responsible for creating a Servlet Filter that replaces the HttpSession implementation with an implementation backed by Spring Session. To do so, add the following Spring Configuration:

Unresolved include directive in modules/ROOT/pages/guides/java-jdbc.adoc - include::example$spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Config.java[]
1 The @EnableJdbcHttpSession annotation creates a Spring Bean with the name of springSessionRepositoryFilter. That bean implements Filter. The filter is in charge of replacing the HttpSession implementation to be backed by Spring Session. In this instance, Spring Session is backed by a relational database.
2 We create a dataSource that connects Spring Session to an embedded instance of an H2 database. We configure the H2 database to create database tables by using the SQL script that is included in Spring Session.
3 We create a transactionManager that manages transactions for previously configured dataSource.

有关如何配置数据访问相关问题的其他信息,请参阅 {docs-url}/spring/docs/{spring-core-version}/reference/html/data-access.html[Spring Framework Reference Documentation]。

For additional information on how to configure data access related concerns, see the {docs-url}/spring/docs/{spring-core-version}/reference/html/data-access.html[Spring Framework Reference Documentation].

Java Servlet Container Initialization

我们的 Spring Configuration 创建了一个名为 springSessionRepositoryFilter 的 Spring Bean,该 Bean 实施了 FilterspringSessionRepositoryFilter Bean 负责使用由 Spring Session 支持的自定义实现来替换 HttpSession

Our httpsession-jdbc-spring-configuration created a Spring bean named springSessionRepositoryFilter that implements Filter. The springSessionRepositoryFilter bean is responsible for replacing the HttpSession with a custom implementation that is backed by Spring Session.

为了让我们的 Filter 发挥其魔力,Spring 需要加载我们的 Config 类。最后,我们需要确保我们的 Servlet 容器(即 Tomcat)针对每个请求使用我们的 springSessionRepositoryFilter。幸运的是,Spring Session 提供了一个名为 AbstractHttpSessionApplicationInitializer 的实用程序类,可以轻松地完成这两步。以下示例显示了如何执行此操作:

In order for our Filter to do its magic, Spring needs to load our Config class. Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our springSessionRepositoryFilter for every request. Fortunately, Spring Session provides a utility class named AbstractHttpSessionApplicationInitializer to make both of these steps easy. The following example shows how to do so:

src/main/java/sample/Initializer.java
Unresolved include directive in modules/ROOT/pages/guides/java-jdbc.adoc - include::example$spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Initializer.java[]

我们的类(Initializer)的名称无关紧要。重要的是我们扩展 AbstractHttpSessionApplicationInitializer

The name of our class (Initializer) does not matter. What is important is that we extend AbstractHttpSessionApplicationInitializer.

1 The first step is to extend AbstractHttpSessionApplicationInitializer. Doing so ensures that the Spring bean named springSessionRepositoryFilter is registered with our Servlet Container for every request.
2 AbstractHttpSessionApplicationInitializer also provides a mechanism to ensure Spring loads our Config.

Multiple DataSources

Spring Session 提供了 @SpringSessionDataSource 限定符,它允许你在 JdbcIndexedSessionRepository 中明确声明应该注入哪个 DataSource bean。这在应用程序上下文中存在多个 DataSource bean 的情况下特别有用。

Spring Session provides the @SpringSessionDataSource qualifier, allowing you to explicitly declare which DataSource bean should be injected in JdbcIndexedSessionRepository. This is particularly useful in scenarios with multiple DataSource beans present in the application context.

以下示例演示了如何执行此操作:

The following example shows how to do so:

Config.java
@EnableJdbcHttpSession
public class Config {

	@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() {
		// ...
	}
}
1 This qualifier declares that firstDataSource is to be used by Spring Session.

httpsession-jdbc Sample Application

本节介绍如何处理 httpsession-jdbc Sample Application。

This section describes how to work with the httpsession-jdbc Sample Application.

Running the httpsession-jdbc Sample Application

您可以获取 源代码 并调用以下命令运行示例:

You can run the sample by obtaining the source code and invoking the following command:

$ ./gradlew :spring-session-sample-javaconfig-jdbc:tomcatRun

您现在应该能够访问 [role="bare"][role="bare"]http://localhost:8080/ 中的应用程序。

You should now be able to access the application at [role="bare"]http://localhost:8080/

Exploring the httpsession-jdbc Sample Application

现在你可以尝试使用此应用程序。为此,请填写以下信息的表单:

Now you can try using the application. To do so, fill out the form with the following information:

  • Attribute Name: username

  • Attribute Value: rob

然后,请点击 Set Attribute 按钮。您现在应该可以看到表中显示的值了。

Now click the Set Attribute button. You should now see the values displayed in the table.

How Does It Work?

我们与 HttpSession 中显示的标准 SessionServlet 进行交互,这在下表中有所说明:

We interact with the standard HttpSession in the SessionServlet shown in the following listing:

src/main/java/sample/SessionServlet.java
Unresolved include directive in modules/ROOT/pages/guides/java-jdbc.adoc - include::example$spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/SessionServlet.java[]

不使用 Tomcat 的 HttpSession,我们在 H2 数据库中永久保存这些值。Spring Session 会在你的浏览器中创建一个名为 SESSION 的 cookie。该 cookie 包含你会话的 ID。你可以使用 ChromeFirefox 查看 cookie。

Instead of using Tomcat’s HttpSession, we persist the values in H2 database. Spring Session creates a cookie named SESSION in your browser. That cookie contains the ID of your session. You can view the cookies (with Chrome or Firefox).

如果你想的话,可以使用位于 [role="bare"][role="bare"]http://localhost:8080/h2-console/ 的 H2 web 控制台来移除会话(为 JDBC URL 使用 jdbc:h2:mem:testdb)。

If you like, you can remove the session by using the H2 web console available at: [role="bare"]http://localhost:8080/h2-console/ (use jdbc:h2:mem:testdb for JDBC URL).

现在,您可以访问 [role="bare"][role="bare"]http://localhost:8080/ 中的应用程序并看到我们添加的属性不再显示。

Now you can visit the application at [role="bare"]http://localhost:8080/ and see that the attribute we added is no longer displayed.