vue获取springboot后台session
时间: 2023-09-03 10:07:32 浏览: 122
要在 Vue 中获取 Spring Boot 后台的 session,需要在后台返回的响应头中设置 session 的信息,然后在 Vue 中可以通过 axios 拦截器获取到响应头中的 session 信息。
在 Spring Boot 中,可以使用 Spring Session 来处理 session,具体操作如下:
1. 引入 Spring Session 的依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
```
2. 配置 Redis
Spring Session 默认使用 Redis 存储 session,需要在 application.properties 文件中配置 Redis:
```properties
spring.redis.host=localhost
spring.redis.port=6379
```
3. 配置 Spring Session
在 Spring Boot 启动类上添加 @EnableRedisHttpSession 注解,开启 Spring Session:
```java
@SpringBootApplication
@EnableRedisHttpSession
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
4. 设置 session
在需要设置 session 的地方,可以使用 HttpServletRequest 的 getSession() 方法来获取 session 对象,然后设置相应的 session 属性:
```java
@Controller
public class TestController {
@GetMapping("/setSession")
@ResponseBody
public String setSession(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("username", "test");
return "session set success";
}
}
```
在 Vue 代码中,可以使用 axios 的拦截器来获取响应头中的 session 信息,具体代码如下:
```javascript
import axios from 'axios';
axios.interceptors.response.use(
response => {
const session = response.headers['session'];
if (session) {
// 将 session 存储到本地
localStorage.setItem('session', session);
}
return response;
},
error => {
return Promise.reject(error);
}
);
```
在需要使用 session 的地方,可以通过 localStorage.getItem('session') 来获取存储在本地的 session 信息。
相关推荐
![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)