springboot保持登录状态
时间: 2023-11-05 16:02:26 浏览: 32
在Spring Boot中,可以使用Spring Security来保持用户登录状态。下面是一些步骤:
1. 添加Spring Security依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 配置Spring Security
在Spring Boot中,可以通过在application.properties或application.yml文件中添加以下配置来启用Spring Security:
```
spring.security.user.name=admin
spring.security.user.password=admin
spring.security.user.roles=admin
```
这将创建一个名为“admin”的用户,密码为“admin”,角色为“admin”。
3. 创建登录页面
在Spring Boot中,可以使用Thymeleaf来创建登录页面。创建一个名为“login.html”的文件,并添加以下代码:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>登录</title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div>
<label>Username:</label>
<input type="text" name="username" />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" />
</div>
<div>
<input type="submit" value="登录" />
</div>
</form>
</body>
</html>
```
4. 配置登录页面和登录成功页面
在application.properties或application.yml文件中添加以下配置:
```
spring.security.login-page=/login
spring.security.default-target-url=/success
```
这将指定登录页面为“/login”,登录成功后将重定向到“/success”页面。
5. 创建成功页面
在Thymeleaf中,可以创建一个名为“success.html”的文件,并添加以下代码:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>登录成功</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
```
6. 测试应用程序
启动Spring Boot应用程序并访问“http://localhost:8080/login”以访问登录页面。在用户名和密码字段中输入“admin”和“admin”,然后单击“登录”按钮。您应该被重定向到“http://localhost:8080/success”,并看到一个“登录成功”消息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)