0
点赞
收藏
分享

微信扫一扫

Web跨域请求及SpringBoot项目解决方案


Web跨域请求及SpringBoot项目解决方案_过滤器



SpringBoot项目解决方案

方法一、SpringBoot的注解@CrossOrigin(也支持SpringMVC)

@RestController
@CrossOrigin
@RequestMapping("/product")
public class ProductController extends BaseController{

@Autowired
private ProductService productService;

}

方法二、将注解@CrossOrigin放在BaseController公共类上

@CrossOrigin
public class BaseController {

}

方法三、处理跨域请求的Configuration
增加一个配置类,WebConfig.java。继承WebMvcConfigurerAdapter或者实现WebMvcConfigurer接口,其他都不用管,项目启动时,会自动读取配置。

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS).maxAge(3600);
}

方法四、采用过滤器(filter)的方式
同方法二加配置类,增加一个CORSFilter 类,并实现Filter接口即可,其他都不用管,接口调用时,会过滤跨域的拦截

@Component
public class CORSFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
// 设置允许Cookie
res.addHeader("Access-Control-Allow-Credentials", "true");
// 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求
res.addHeader("Access-Control-Allow-Origin", "*");
// 设置允许跨域请求的方法
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
// 允许跨域请求包含content-type
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
public void destroy() {
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}

方法五:CORSFilter解决前端跨域请求问题,效果最好

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
* author: lovoo
* Date:2019/12/12
* Time:11:01
*/
@Configuration
public class GlobalCorsConfig {

@Bean
public CorsWebFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
//2.是否发送Cookie信息
config.setAllowCredentials(true);
//3.有效时间
config.setMaxAge(3600L);
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//4.返回新的CorsFilter.
return new CorsWebFilter(configSource);
}
}

方法六、使用nginx

将前端项目与后台项目网关配置在nginx中

Web跨域请求及SpringBoot项目解决方案_过滤器_02

QQ群:722865146
分布式商城下载:https://gitee.com/charlinchenlin/wysmall


举报

相关推荐

0 条评论