赞
踩
@CrossOrigin
注解在Controller层对应的方法上添加@CrossOrigin或者类上添加@CrossOrigin
- @RestController
- @RequestMapping("index")
- public class IndexController {
-
- @GetMapping("/test")
- @CrossOrigin
- public String index() {
- return "hello world";
- }
- }
新建配置类CorsConfig,创建CorsFilter
过滤器,允许跨域
- @Configuration
- public class CorsConfig {
- // 跨域请求处理
- @Bean
- public CorsFilter corsFilter() {
- CorsConfiguration config = new CorsConfiguration();
- //允许所有域名进行跨域调用
- config.addAllowedOrigin("*");
- //允许所有请求头
- config.addAllowedHeader("*");
- //允许所有方法
- config.addAllowedMethod("*");
- // 添加映射路径,我们拦截一切请求
- UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- source.registerCorsConfiguration("/**", config);
- return new CorsFilter(source);
- }
- }
WebMvcConfigurer
,重写addCorsMappings
方法- @Configuration
- public class CorsConfig implements WebMvcConfigurer {
- // 跨域请求处理
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry
- // 设置允许跨域的路径
- .addMapping("/**")
- // 设置允许跨域请求的域名
- .allowedOriginPatterns("*")
- // 是否允许证书
- .allowCredentials(true)
- // 设置允许的方法
- .allowedMethods("GET", "POST", "DELETE", "PUT")
- // 设置允许的header属性
- .allowedHeaders("*")
- // 跨域允许时间
- .maxAge(3600);
- }
- }
全局配置有可能出先跨域失败的情况,改为过滤器解决跨域问题之后就解决了,在此附上过滤器跨域代码:
- @Component
- public class CorsFilter implements Filter {
-
- //销毁时候调用的方法
- @Override
- public void destroy() {
-
- }
-
- @Override
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
- throws IOException, ServletException {
-
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse) res;
-
- response.setHeader("Access-Control-Allow-Origin", "*");
- response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
- response.setHeader("Access-Control-Max-Age", "3600");
- response.setHeader("Access-Control-Allow-Headers", "*");
-
- chain.doFilter(req, res);
-
- }
-
- //初始化调用的方法
- //当服务器 被启动的时候,调用
- @Override
- public void init(FilterConfig arg0) throws ServletException {
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。