springboot保持登录状态
时间: 2023-08-29 07:05:38 浏览: 34
在Spring Boot中保持登录状态的常用方法是使用Session或者Token。
1. 使用Session
Session是一种服务器端的机制,用于在服务器端存储用户的信息。在用户登录成功后,可以将用户信息存储在Session中,当用户进行其他操作时,可以从Session中获取用户信息判断用户是否已经登录。
代码示例:
```java
@RequestMapping("/login")
public String login(HttpServletRequest request, String username, String password) {
if ("admin".equals(username) && "123456".equals(password)) {
request.getSession().setAttribute("user", username);
return "success";
} else {
return "fail";
}
}
@RequestMapping("/index")
public String index(HttpServletRequest request) {
Object user = request.getSession().getAttribute("user");
if (user != null) {
return "index";
} else {
return "login";
}
}
```
2. 使用Token
Token是一种在客户端和服务器端之间传递信息的方式,通常使用JWT(JSON Web Token)实现。在用户登录成功后,服务器端会生成一个Token,并将Token返回给客户端,客户端每次请求时都需要带上Token,服务器端根据Token判断用户是否已经登录。
代码示例:
```java
@RequestMapping("/login")
public String login(String username, String password) {
if ("admin".equals(username) && "123456".equals(password)) {
String token = JwtUtils.createToken(username);
return token;
} else {
return "fail";
}
}
@RequestMapping("/index")
public String index(String token) {
boolean isLogin = JwtUtils.verifyToken(token);
if (isLogin) {
return "index";
} else {
return "login";
}
}
```
以上两种方法都可以实现登录状态的保持,选择哪种方法取决于具体的业务场景。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)