Spring Session - Spring Boot
本指南介紹如何在使用 Spring Boot 時,利用 Spring Session 透明地使用關係型資料庫來支援 Web 應用程式的 HttpSession。
| 你可以在 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 會自動使用該儲存實現。如果你有多個實現,則必須選擇要用於儲存會話的 StoreType,如上所示。
在底層,Spring Boot 應用的配置相當於手動新增 @EnableJdbcHttpSession 註解。這將建立一個名為 springSessionRepositoryFilter 的 Spring bean。該 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 文件的配置 DataSource 部分。
Servlet 容器初始化
我們的Spring Boot 配置建立了一個名為 springSessionRepositoryFilter 的 Spring bean,該 bean 實現了 Filter。springSessionRepositoryFilter bean 負責將 HttpSession 替換為由 Spring Session 支援的自定義實現。
為了讓我們的 Filter 發揮作用,Spring 需要載入我們的 Config 類。最後,我們需要確保我們的 Servlet 容器(即 Tomcat)對每個請求都使用我們的 springSessionRepositoryFilter。幸運的是,Spring Boot 為我們處理了這兩個步驟。
httpsession-jdbc-boot 示例應用程式
httpsession-jdbc-boot 示例應用程式演示瞭如何在您使用 Spring Boot 時,利用 Spring Session 透明地使用 H2 資料庫來支援 Web 應用程式的 HttpSession。
執行 httpsession-jdbc-boot 示例應用程式
您可以透過獲取原始碼並呼叫以下命令來執行示例:
$ ./gradlew :spring-session-sample-boot-jdbc:bootRun
您現在應該能夠透過 localhost:8080/ 訪問該應用程式
探索安全示例應用程式
現在你可以嘗試使用該應用程式。為此,輸入以下內容進行登入:
-
使用者名稱 user
-
密碼 password
現在點選登入按鈕。您應該會看到一條訊息,指示您已使用之前輸入的使用者登入。使用者的憑據儲存在 H2 資料庫中,而不是 Tomcat 的 HttpSession 實現中。
它是如何工作的?
我們不使用 Tomcat 的 HttpSession,而是將值持久化到 H2 資料庫中。Spring Session 將 HttpSession 替換為由關係型資料庫支援的實現。當 Spring Security 的 SecurityContextPersistenceFilter 將 SecurityContext 儲存到 HttpSession 時,它隨後會被持久化到 H2 資料庫中。
當建立一個新的 HttpSession 時,Spring Session 會在您的瀏覽器中建立一個名為 SESSION 的 Cookie。該 Cookie 包含您會話的 ID。您可以使用 Chrome 或 Firefox 檢視 Cookie。
你可以透過 H2 web 控制檯刪除會話,網址為:localhost:8080/h2-console/(JDBC URL 使用 jdbc:h2:mem:testdb)。
現在你可以訪問應用程式 localhost:8080/,然後看到我們不再被認證。