Spring Session Module provides APIs and implementation for managing user session in a web application.

Spring Session Module提供用于管理Web应用程序中用户会话的API和实现。

Spring会议 (Spring Session)

Spring Session consists of following modules:

Spring Session由以下模块组成:

  1. Spring Session Core: Provides API and core support for session management.Spring Session Core:为会话管理提供API和核心支持。
  2. Spring Session JDBC: provides session management using relational database.Spring Session JDBC:使用关系数据库提供会话管理。
  3. Spring Session Data Redis: provides session management implementation for Redis database.Spring Session Data Redis:为Redis数据库提供会话管理实现。
  4. Spring Session Hazelcast: provides session management support using Hazelcast.Spring Session Hazelcast:使用Hazelcast提供会话管理支持。

Spring会议的好处 (Spring Session Benefits)

  • Spring Session decouples session management logic from the application, making it more fault tolerant.Spring Session将会话管理逻辑与应用程序分离开来,从而使其更具容错能力。
  • Spring Session keeps user session information in the database, so it’s great to use in a clustered environment with multiple server nodes. We don’t need the sticky session or session replication logic.Spring Session将用户会话信息保留在数据库中,因此,在具有多个服务器节点的集群环境中使用它非常好。 我们不需要粘性会话或会话复制逻辑。
  • User session data is not lost if the application crashes. When the application is started again it picks up all the user session data.如果应用程序崩溃,则用户会话数据不会丢失。 再次启动该应用程序时,它将获取所有用户会话数据。
  • It’s easy to switch between session storage software, just by changing some configuration we can switch from using Redis to JDBC.在会话存储软件之间切换很容易,只需更改一些配置,我们就可以从使用Redis切换到JDBC 。
  • Spring is an open source project and easily bootstrapped. If you face any issues, there is a good chance that you will find the solution easily online.Spring是一个开源项目,很容易引导。 如果您遇到任何问题,很有可能会在网上轻松找到解决方案。

Spring Session JDBC示例 (Spring Session JDBC Example)

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数据库。 因此,我们需要在项目中遵循以下依赖关系。

  • spring-boot-starter-web: It’s a spring mvc web application.spring-boot-starter-web:这是一个Spring MVC Web应用程序。
  • spring-boot-starter-jdbc: For Spring Boot JDBC support and auto configuration.spring-boot-starter-jdbc:用于Spring Boot JDBC支持和自动配置。
  • spring-boot-starter-thymeleaf: This is to support Thymeleaf for our view pages. Thymeleaf is simple to use and provides good integration with Spring framework.spring-boot-starter-thymeleaf:这是为了在我们的视图页面上支持Thymeleaf。 Thymeleaf易于使用,并与Spring框架提供良好的集成。
  • spring-session-core: Spring Session Core APIspring-session-core:Spring Session Core API
  • spring-session-jdbc: Spring Session JDBC Implementationspring-session-jdbc:Spring Session JDBC实现
  • mysql-connector-java: MySQL JDBC Driver Jarmysql-connector-java:MySQL JDBC驱动程序Jar

Here is our final pom.xml file:

这是我们最终的pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.journaldev.spring</groupId><artifactId>Spring-Session-Example</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>Spring-Session-Example</name><description>Spring Session Example</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.3.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>10</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-core</artifactId></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

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.

让我们一一看一下每个组件。

application.properties (application.properties)

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=journaldevspring.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文件中提供的脚本手动创建数据库表。

index.html (index.html)

Here is our view page built using Thymeleaf.

这是我们使用Thymeleaf构建的视图页面。

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Session JDBC Example</title>
</head>
<body><div><form th:action="@{/saveMessage}" method="post"><textarea name="msg" cols="40" rows="2"></textarea><br> <input type="submit" value="Save Message" /></form></div><div><h2>Messages</h2><ul th:each="m : ${messages}"><li th:text="${m}">msg</li></ul></div><div><form th:action="@{/invalidate}" method="post"><input type="submit" value="Destroy Session" /></form></div>
</body>
</html>

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.

最后,有一个按钮可以使会话无效并销毁会话。 一旦会话被销毁,它的属性将被删除,您将看不到之前保存的消息。

HomeController.java (HomeController.java)

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<String> msgs = (List<String>) 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<String> msgs = (List<String>) 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框架的优点,它将自动配置我们的应用程序以使用数据库进行会话管理。

SpringSessionExampleApplication.java (SpringSessionExampleApplication.java)

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);}
}

Spring Session JDBC测试 (Spring Session JDBC Test)

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.

下面的屏幕录像显示了执行应用程序时的输出。

摘要 (Summary)

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是一个很棒的模块,它将会话管理逻辑与应用程序逻辑分开。 它使我们的应用程序具有容错能力,并减少了内存使用量。 它非常容易实现,最适合于集群环境。

GitHub Repository.GitHub Repository下载示例代码。

翻译自: https://www.journaldev.com/21748/spring-session-management-spring-session-jdbc

Spring Session Management – Spring Session JDBC相关推荐

  1. session传递参数_分布式 Session 之 Spring Session 架构与设计

    作者 | 李增光 杏仁后端工程师.「只有变秃,才能变强!」 ​前言 开始进行 Web 开发时,我们可能会遇到这样的情况,当服务器重启之后,之前的登录状态会失效需要重新登录.又或者你的应用程序部署了不止 ...

  2. .netcore 如何获取系统中所有session_集群化部署,Spring Security 要如何处理 session 共享?

    前面和大家聊了 Spring Security 如何像 QQ 一样,自动踢掉已登录用户(Spring Boot + Vue 前后端分离项目,如何踢掉已登录用户?),但是前面我们是基于单体应用的,如果我 ...

  3. Spring MVC集成Spring Data Reids和Spring Session实现Session共享

    说明:Spring MVC中集成Spring Data Redis和Spring Session时版本是一个坑点,比如最新版本的Spring Data Redis已经不包含Jedis了,需要自行引入. ...

  4. [译]Spring Session 与 Spring Security

    原文:http://docs.spring.io/spring-session/docs/current-SNAPSHOT/reference/html5/guides/security.html 本 ...

  5. 利用spring session解决共享Session问题

    https://blog.csdn.net/patrickyoung6625/article/details/45694157 1.共享Session问题 HttpSession是通过Servlet容 ...

  6. Spring Session - Cookie VS Session VS Token 以及 Session不一致问题的N种解决方案

    文章目录 Cookie VS Session VS Token History Cookie Session Token Session不一致问题 Session不一致解决方案 nginx sessi ...

  7. Spring Security——集成Spring Session、Redis和JSON序列化解决方案

    官方文档 https://docs.spring.io/spring-session/docs/2.4.2/reference/html5/#spring-security Maven 主要 < ...

  8. spring 控制hibernate的session何时关闭.

    http://blog.csdn.net/dengyin2000/article/details/448341 在用spring管理hierbernate的事务我们一般都用TransactionPro ...

  9. 单点登录实现(spring session+redis完成session共享)

    一.前言 项目中用到的SSO,使用开源框架cas做的.简单的了解了一下cas,并学习了一下 单点登录的原理,有兴趣的同学也可以学习一下,写个demo玩一玩. 二.工程结构 我模拟了 sso的客户端和s ...

最新文章

  1. android资源包混淆,Android---andresguard资源混淆
  2. 笔记本电脑打开后不显示桌面_宝骏630打开空调开关后压缩机不工作 - 汽车空调...
  3. 网络编程知识预备(3) ——SOCKET、TCP、HTTP之间的区别与联系
  4. Linux下解压缩命令
  5. 移动办公、企业-移动办公:移动过程中的办公触手可及-by小雨
  6. 精通javascript、javascript语言精粹读书笔记
  7. 每天Leetcode 刷题 初级算法篇-汉明距离
  8. stdafx有什么用(包含相关问题分析)
  9. 硬盘录像机常见问题解答硬盘录像机故障解决
  10. cad怎样弄出放线的坐标_怎么把图纸上的坐标输入CAD详细步骤?
  11. 腾讯看点App正式下线
  12. 【JAVA操作系统——可变式分区分配】首次适应算法
  13. php页面劫持网站,网站被劫持了怎么修复
  14. 如何破“万事开头难”?试试这三招
  15. 洛谷 P4643 [国家集训队]阿狸和桃子的游戏
  16. android 首字母 验证码,Android 验证码功能实现代码
  17. 《小猪佩奇拜年歌》在QQ音乐和网易云音乐上线
  18. 学习记录 重叠网络权威知识——多尺度复杂网络社区发现的链接
  19. Maven发布轻量二方包
  20. windows 程序设计 第三章读书笔记(上)

热门文章

  1. 给自己的电脑做一个O盘 -隐藏自己私密的东
  2. [转载] Python input()函数
  3. [转载] Python使用QRCode生成二维码
  4. java获取当前行数
  5. BM求线性递推模板(杜教版)
  6. OO Summary (Homework 5-7)
  7. JavaWeb之多语言国际化
  8. 鼠标悬浮缩放--鼠标悬浮图片上图片进行放大突出
  9. 第四章 jQuery文档处理
  10. ASP.NET2.0 分页控件 PagerPro.dll (1.1.0 最新)