首页 > 编程语言 > 详细

Springboot设置跨域的三种方式

时间:2019-05-17 10:23:12      阅读:118      评论:0      收藏:0      [点我收藏+]

方式一(精细配置)

在需要跨域的整个Controller或者单个方法上添加@CrossOrigin注解

方式二(全局配置)

 1 @Configuration
 2 public class WebMvcConfig extends WebMvcConfigurerAdapter {
 3     @Override
 4     public void addCorsMappings(CorsRegistry registry) {
 5         registry.addMapping("/**")
 6                 .allowedOrigins("*")
 7                 .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
 8                 .maxAge(3600)
 9                 .allowCredentials(true);
10     }
11 }

方式三(通过filter)

 1 @Component
 2 @WebFilter(urlPatterns = "/*", filterName = "authFilter") //这里的“/*” 表示的是需要拦截的请求路径
 3 public class PassHttpFilter implements Filter {
 4     @Override
 5     public void init(FilterConfig filterConfig) throws ServletException { }
 6     @Override
 7     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
 8         HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
 9         httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
10         httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
11         httpResponse.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
12         filterChain.doFilter(servletRequest, httpResponse);
13     }
14     @Override
15     public void destroy() { }
16 }

 

Springboot设置跨域的三种方式

原文:https://www.cnblogs.com/yhcjhun/p/10879690.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!