Spring Boot Session 会话管理示例

Spring Boot Session Management tutorial (2022) with Code Example | TechGeekNxt >> Jan 28, 2022 - In this article, we will discuss how to handle Spring Boot Sessionhttps://www.techgeeknext.com/spring-boot/spring-boot-session-management

实现 Spring Boot 会话管理的步骤,将在本教程中介绍。

  1. 从 Spring Initializer 创建 Spring Boot 项目。
  2. 在 pom.xml 中添加 Spring Session jdbc 依赖
  3. 在 application.properties 中添加 spring jdbc 属性
  4. 创建休息端点以保存、销毁/使会话无效。

什么是会话管理?

会话管理是安全地处理来自单个用户或实体对基于 Web 的应用程序或服务的多个请求的过程。HTTP 用于网站和浏览器之间的通信,会话是由同一用户创建的一系列 HTTP 请求和事务。会话管理实现指定了在用户和 Web 应用程序之间共享和不断交换会话 ID 的过程。

注意:Spring boot 会话管理示例的完整源代码可以在文末下载。

您还可以学习如何使用 Spring Boot + JWT Token 对用户进行身份验证。



由于 HTTP 协议是无状态的,并且为了跟踪客户行为,我们需要会话管理。会话管理是一个 Web 容器框架,用于存储特定用户的会话数据。

您可以通过以下方式之一处理会话:

  1. 饼干

    是从网站发送并在用户浏览时由用户的网络浏览器保存在用户计算机上的数据。
  2. 隐藏的表单域

    是隐藏数据,不会显示给用户,也不能修改。但是,当用户提交表单时,会发送隐藏数据。
  3. 网址重写

    是修改URL参数的方法。
  4. HttpSession

    使数据能够与个别访问者相关联。

您可以通过将静态或经常请求的数据存储在内存/缓存提供程序中来进一步提高应用程序的性能。 请参阅 Spring Boot 缓存示例以了解更多信息。

在大多数 Web 应用程序中,管理用户会话非常重要。主要是我们一直在集群环境中维护用户会话数据,在服务器节点前面使用负载均衡器来相应地分配流量。因此,像在生产中一样管理会话环境将非常关键。在分布式环境中,我们可以通过以下方式管理会话。

  • 粘性会话

    在这种类型的会话中,负载均衡器总是将相同的客户端请求路由到相同的节点。但是在这里,如果该节点出现故障,会话也将消失。
  • 会话复制

    为了克服粘性会话问题,会话复制将会话数据复制到多个服务器。因此,如果任何节点出现故障,会话数据将始终可用于其他节点。
  • 持久数据存储中的会话数据

    在这种情况下,会话不会存储在服务器内存中,而是存储在具有唯一 ID 称为 SESSION_ID 的数据库(RDBMS、Redis、HazelCast、MongoDB 等)中。

 

如果您想在创建或删除 HTTP 会话时执行某些重要任务,请使用Spring Boot + 会话侦听器示例。

Spring Session 中包含以下模块:

  1. 春季会议核心

    - Spring Session 核心 API
  2. Spring Session 数据 Redis

    - 为Redis数据库会话管理 提供会话存储库
  3. 春季会话 JDBC

    - 为关系数据库(如 MYSQL 等会话管理 )提供会话存储库。
  4. 春季会议榛树

    - 为Hazelcast会话管理提供会话存储库。

默认情况下,Apache Tomcat 将对象存储在内存中以进行 HTTP 会话管理。此外,为了管理 Spring Boot 会话管理,HTTPSession 将用于使用Spring Session JDBC将会话信息存储在持久存储(Mysql)中。

在本教程中,将看到如何使用 JDBC Session 使用 Spring Boot Session Management

(To achieve Spring Boot Session Management using Redis, refer this example.)

 

我们不必编写任何代码来将会话对象写入 MySQL 服务器,如下所示,只需使用以下属性。

spring.session.store-type=jdbc

Spring Boot Session JDBC 提供由关系数据库和配置支持支持的 SessionRepository 实现。

 


项目将如下所示:

 

创建 Spring Boot Rest 应用程序


 

  • 去 Spring 官网https://start.spring.io/
  • 选择Maven项目,添加依赖
  • 单击生成项目按钮。
  • 在 Eclipse IDE 中将此生成的项目作为现有的 maven 项目导入,然后按照以下步骤操作。

 


在 pom.xml 中添加 Spring Session jdbc 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.8.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.techgeeknext</groupId>
	<artifactId>SpringBootSessionManagement</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootSessionManagement</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</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>

创建主类

- SpringBootSessionManagementApplication

package com.techgeeknext;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootSessionManagementApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSessionManagementApplication.class, args);
	}
}

创建控制器

处理用户请求,处理用户数据并将数据存储在会话中的NOTES_SESSION 属性中。

package com.techgeeknext.controller;

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 SpringBootSessionController {
    @PostMapping("/addNote")
    public String addNote(@RequestParam("note") String note, HttpServletRequest request) {
        //get the notes from request session
        List<String> notes = (List<String>) request.getSession().getAttribute("NOTES_SESSION");
        //check if notes is present in session or not
        if (notes == null) {
            notes = new ArrayList<>();
            // if notes object is not present in session, set notes in the request session
            request.getSession().setAttribute("NOTES_SESSION", notes);
        }
        notes.add(note);
        request.getSession().setAttribute("NOTES_SESSION", notes);
        return "redirect:/home";
    }
    @GetMapping("/home")
    public String home(Model model, HttpSession session) {
        List<String> notes = (List<String>) session.getAttribute("NOTES_SESSION");
        model.addAttribute("notesSession", notes!=null? notes:new ArrayList<>());
        return "home";
    }
    @PostMapping("/invalidate/session")
    public String destroySession(HttpServletRequest request) {
        //invalidate the session , this will clear the data from configured database (Mysql/redis/hazelcast)
        request.getSession().invalidate();
        return "redirect:/home";
    }
}


在application.properties中添加以下配置属性

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springBootSession?createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always
spring.session.timeout.seconds=600
spring.h2.console.enabled=true

创建 home.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Session Management Example</title>
</head>
<body>
	<div>
		<form th:action="@{/addNote}" method="post">
			<textarea name="note" cols="40" rows="2"></textarea>
			<br> <input type="submit" value="Add Note" />
		</form>
	</div>
	<div>
		<form th:action="@{/invalidate/session}" method="post">
			<input type="submit" value="Destroy Session" />
		</form>
	</div>
	<div>
		<h2>Notes</h2>
		<ul th:each="note : ">
			<li th:text="">note</li>
		</ul>
	</div>

</body>
</html>

我们的演示已经准备好,现在编译并运行 SpringBootSessionManagementApplication.java 并进入主页 http://localhost:8080/home。


在 Textarea 中输入 Note 并单击 Add Note 按钮以在会话中添加注释 转到主页,注释已添加到会话中。 在会话中添加第二个注释。

 

 

  1. spring_session

 

  1. spring_session_attributes



点击 Destroy Session,Spring Boot 会从 spring_session_attributes 表中删除数据(NOTES_SESSION)。 现在转到主页,会话数据已被清理。

 

 

 

正如您所见,Spring boot 如何将用户会话数据存储到数据库中,这也使得在集群环境中维护会话数据变得非常容易。

下载源代码

本文的完整源代码可以在下面找到。
在此处下载 - Spring Boot 会话管理

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个非常流行的 Java Web 框架,SIP(Session Initiation Protocol)是一种信令协议,用于建立、修改和终止多媒体会话,如语音电话、视频电话和即时消息等。Spring Boot 可以与 SIP 协议配合使用,提供一个完整的 SIP 应用程序。 以下是一个简单的 Spring Boot SIP 示例: 1. 添加 Maven 依赖 ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-sip</artifactId> <version>2.5.2</version> </dependency> ``` 2. 创建一个 SipServlet ``` import javax.servlet.annotation.WebServlet; import javax.servlet.sip.SipServlet; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; @WebServlet(name = "SipServlet", urlPatterns = "/sip/*") public class MySipServlet extends SipServlet { @Override protected void doInvite(SipServletRequest request) throws ServletException, IOException { // 处理 INVITE 请求 } @Override protected void doResponse(SipServletResponse response) throws ServletException, IOException { // 处理响应 } @Override protected void doRegister(SipServletRequest request) throws ServletException, IOException { // 处理 REGISTER 请求 } } ``` 3. 创建一个 SipConfig ``` import javax.servlet.sip.SipServlet; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass(SipServlet.class) public class SipConfig { @Bean @ConditionalOnMissingBean(SipServlet.class) public SipServlet sipServlet() { return new MySipServlet(); } @Bean public ServletRegistrationBean<SipServlet> sipServletRegistration() { return new ServletRegistrationBean<>(sipServlet(), "/sip/*"); } } ``` 4. 运行应用程序 现在,您可以在浏览器中访问 `http://localhost:8080/sip`,就可以启动 SIP 应用程序了。 这是一个简单的 Spring Boot SIP 示例,您可以根据实际需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值