SpringBoot跨域Access-Control-Allow-Origin实现解析
这篇文章主要介绍了SpringBoot跨域Access-Control-Allow-Origin实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
跨域(CORS)是指不同域名之间相互访问。
跨域,指的是浏览器不能执行其他网站的脚本,它是由浏览器的同源策略所造成的,是浏览器对于JavaScript所定义的安全限制策略。
只要协议,子域名,主域名,端口号有一项不同,就属于跨域
跨域的解决方法
前端:
使用jsonp
后端:
实现WebMvcConfigurer接口
在需要跨域访问的类和方法中设置允许跨域访问(注解)
服务端设置ResponseHeader(Fiter)
(1)实现WebMvcConfigurer接口
通过实现WebMvcConfigurer接口中的addCorsMappings()方法来实现跨域
@Configuration publicclassWebMvcConfigimplementsWebMvcConfigurer{ //解决跨域问题 @Override publicvoidaddCorsMappings(CorsRegistryregistry){ registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET","POST","DELETE","PUT") .maxAge(3600); } }
(2)注解
使用@CrossOrigin注解声明类和方法允许跨域访问
该注解可以实现方法级别的细粒度的跨域控制。可以在类或者方添加该注解。
如果在类上添加该注解,该类下的所有接口都可以通过跨域访问;
如果在方法上添加注解,那么只限于加注解的方法可以访问。
@CrossOrigin @RestController @RequestMapping("/api/ppt") publicclassPPTOperation{ @PostMapping("/combine") publicResultcombine(@RequestBodyJSONObjectjsonParam){ …… } }
(3)实现Fiter接口
通过实现Fiter接口在请求中添加一些Header来解决跨域的问题
@Component publicclassCorsFilterimplementsFilter{ @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain) throwsIOException,ServletException{ HttpServletResponseres=(HttpServletResponse)response; res.addHeader("Access-Control-Allow-Credentials","true"); res.addHeader("Access-Control-Allow-Origin","*"); res.addHeader("Access-Control-Allow-Methods","GET,POST,DELETE,PUT"); res.addHeader("Access-Control-Allow-Headers","Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN"); if(((HttpServletRequest)request).getMethod().equals("OPTIONS")){ response.getWriter().println("ok"); return; } chain.doFilter(request,response); } @Override publicvoiddestroy(){ } @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。