問題: 前端跨域訪問後端接口, 在瀏覽器的安全策略下默認是不攜帶cookie的, 因此每次請求都開啓了一次新的會話. 前端
在後臺打印sessionID咱們會發現, 每次請求的sessionID都是不一樣的, 既然每次請求都是一個新的會話, 那咱們去獲取session的時候天然就是null了.vue
解決辦法以下: java
環境: ios
vue 2.0web
springboot 2.1.6spring
1、前端部分
1. 在vue引入axios的位置添加如下代碼axios
import axios from 'axios' axios.defaults.withCredentials = true;// 容許跨域攜帶cookie
2、後臺部分
1. 新建一個FilterConfig類, 編寫一個攔截器類後端
/** * 容許跨域請求 * @author Administrator * */ import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.*; @Component public class FilterConfig implements HandlerInterceptor{ public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));//支持跨域請求 response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域 response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token return true; } }
2. 在建立一個SpringMVCConfig類, 請用攔截器跨域
/** * 啓用跨域配置 * 編寫SpringMVCConfig類使用FilterConfig中的配置 * @author Administrator * */ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SuppressWarnings("deprecation") @SpringBootConfiguration public class SpringMVCConfig extends WebMvcConfigurerAdapter{ @Autowired private FilterConfig filterConfig; public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(filterConfig).addPathPatterns("/**"); } }
問題解決, 重啓工程後咱們再次打印每次請求的sessionID就會發現sessionID是一致的, 固然也就能夠獲取咱們存入session的內容了.瀏覽器
System.out.println(request.getSession().getId());