问题: 前端跨域访问后端接口, 在浏览器的安全策略下默认是不携带cookie的, 所以每次请求都开启了一次新的会话.
在后台打印sessionid我们会发现, 每次请求的sessionid都是不同的, 既然每次请求都是一个新的会话, 那我们去获取session的时候自然就是null了.
解决办法如下:
环境:
vue 2.0
springboot 2.1.6
1. 在vue引入axios的位置添加以下代码
import axios from 'axios' axios.defaults.withcredentials = true;// 允许跨域携带cookie
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());
如对本文有疑问, 点击进行留言回复!!
利用python将Mysql信息以Excel文件并作为邮件附件发送
springmvc+mybaits+mysql上传表情Incorrect string value: ‘\xF0\x9F\xA4\xB4\xF0\x9F...‘ for
SpringCloud Greenwich集成Seata1.2.0详解说明(原创by ulwfcyvi)
mybatis generator生成代码库 与指定的库不一致 为其他库的同名表
网友评论