Spring Session Module provides APIs and implementation for managing user session in a web application.
Spring Session Module提供用于管理Web应用程序中用户会话的API和实现。
Spring Session consists of following modules:
Spring Session由以下模块组成:
Let’s create a simple Spring Session JDBC example project. I will use Spring Boot and MySQL database in the application. So we would need following dependencies in our project.
让我们创建一个简单的Spring Session JDBC示例项目。 我将在应用程序中使用Spring Boot和MySQL数据库。 因此,我们需要在项目中遵循以下依赖关系。
Here is our final pom.xml file:
这是我们最终的pom.xml文件:
4.0.0
com.journaldev.spring
Spring-Session-Example
0.0.1-SNAPSHOT
jar
Spring-Session-Example
Spring Session Example
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
10
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.session
spring-session-core
org.springframework.session
spring-session-jdbc
mysql
mysql-connector-java
org.springframework.boot
spring-boot-maven-plugin
You can generate the base maven project using Spring Initializr and then add required dependencies.
您可以使用Spring Initializr生成基础Maven项目,然后添加所需的依赖项。
Below image shows the final project structure from Spring Tool Suite.
下图显示了Spring Tool Suite的最终项目结构。
Let’s look at each of the components one by one.
让我们一一看一下每个组件。
This is where we specify our database configuration and some spring session attributes.
这是我们指定数据库配置和一些spring会话属性的地方。
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/SpringSessionDB
spring.datasource.username=journaldev
spring.datasource.password=journaldev
spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always
spring.session.timeout.seconds=900
I am specifying spring.session.jdbc.initialize-schema
to always
so that Spring will create the required tables for us.
我将spring.session.jdbc.initialize-schema
指定为always
以便Spring为我们创建所需的表。
Usually, in the production environment, the application user doesn’t have the privilege to execute DDL statements, in that case, set this attribute to never
and create database tables manually from the scripts provided in the JAR file.
通常,在生产环境中,应用程序用户没有执行DDL语句的特权,在这种情况下,请将此属性设置为never
然后使用JAR文件中提供的脚本手动创建数据库表。
Here is our view page built using Thymeleaf.
这是我们使用Thymeleaf构建的视图页面。
Spring Session JDBC Example
Messages
- msg
Notice that /saveMessage
will be used to send message to server. We will save this message to user session attribute.
请注意, /saveMessage
将用于向服务器发送消息。 我们将把此消息保存到用户会话属性。
When the home page is requested, messages
attribute will be set to model. So if the user session is valid, we should see all the messages saved on the home page. Spring session uses Cookies to identify user session, so if you hit reload then also you will see all the earlier saved messages.
当请求主页时, messages
属性将设置为model。 因此,如果用户会话有效,则应该在主页上看到所有已保存的消息。 Spring会话使用Cookies来标识用户会话,因此,如果您点击reload,那么您还将看到所有先前保存的消息。
Finally, there is a button to invalidate and destroy the session. Once the session is destroyed, it’s attribute will get deleted and you won’t see the earlier saved messages.
最后,有一个按钮可以使会话无效并销毁会话。 一旦会话被销毁,它的属性将被删除,您将看不到之前保存的消息。
This is our controller class where we are handling user requests and saving the message to user session attribute.
这是我们的控制器类,在其中处理用户请求并将消息保存到用户会话属性。
package com.journaldev.spring;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model, HttpSession session) {
@SuppressWarnings("unchecked")
List msgs = (List) session.getAttribute("MY_MESSAGES");
if (msgs == null) {
msgs = new ArrayList<>();
}
model.addAttribute("messages", msgs);
return "index";
}
@PostMapping("/saveMessage")
public String saveMessage(@RequestParam("msg") String msg, HttpServletRequest request) {
@SuppressWarnings("unchecked")
List msgs = (List) request.getSession().getAttribute("MY_MESSAGES");
if (msgs == null) {
msgs = new ArrayList<>();
request.getSession().setAttribute("MY_MESSAGES", msgs);
}
msgs.add(msg);
request.getSession().setAttribute("MY_MESSAGES", msgs);
return "redirect:/";
}
@PostMapping("/invalidate")
public String destroySession(HttpServletRequest request) {
request.getSession().invalidate();
return "redirect:/";
}
}
Most of the logic is straightforward, notice that we are not using anything from Spring Session module. This is the beauty of spring framework, it will automatically configure our application to use the database for session management.
大多数逻辑很简单,请注意,我们没有使用Spring Session模块中的任何东西。 这是spring框架的优点,它将自动配置我们的应用程序以使用数据库进行会话管理。
Just a Spring Boot Application to run our application.
只是一个Spring Boot应用程序来运行我们的应用程序。
package com.journaldev.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSessionExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSessionExampleApplication.class, args);
}
}
Our application is ready, just run SpringSessionExampleApplication
class as java application. You will notice following mappings in the console logs.
我们的应用程序已准备就绪,只需将SpringSessionExampleApplication
类作为Java应用程序运行SpringSessionExampleApplication
。 您会在控制台日志中注意到以下映射。
Mapped "{[/saveMessage],methods=[POST]}" onto public java.lang.String com.journaldev.spring.HomeController.saveMessage(java.lang.String,javax.servlet.http.HttpServletRequest)
Mapped "{[/invalidate],methods=[POST]}" onto public java.lang.String com.journaldev.spring.HomeController.destroySession(javax.servlet.http.HttpServletRequest)
Mapped "{[/],methods=[GET]}" onto public java.lang.String com.journaldev.spring.HomeController.home(org.springframework.ui.Model,javax.servlet.http.HttpSession)
You will also notice logger for execution of SQL script to create database tables.
您还将注意到记录器执行SQL脚本以创建数据库表。
Executing SQL script from class path resource [org/springframework/session/jdbc/schema-mysql.sql]
You can check these tables in the database too.
您也可以在数据库中检查这些表。
Our index.html page will be automatically configured as the welcome page, as seen in the logs.
如日志所示,我们的index.html页面将被自动配置为欢迎页面。
2018-06-27 12:50:09.761 INFO 1666 --- [main] o.s.b.a.w.s.WelcomePageHandlerMapping: Adding welcome page template: index
Below screen recording shows the output when the application is executed.
下面的屏幕录像显示了执行应用程序时的输出。
Spring Session is an awesome module that separates session management logic from application logic. It makes our application fault-tolerant and reduces memory usage. It’s very easy to implement and best suited for the clustered environment.
Spring Session是一个很棒的模块,它将会话管理逻辑与应用程序逻辑分开。 它使我们的应用程序具有容错能力,并减少了内存使用量。 它非常容易实现,最适合于集群环境。
翻译自: https://www.journaldev.com/21748/spring-session-management-spring-session-jdbc