springboot跨域请求访问的配置方法
跨域请求是指当前发起请求的域,与该请求指向的资源所在的域不同的请求,这里的同域指的是 “协议 + 域名 + 端口号” 均相同,那么就是同域
#前端以5500端口启动了一个服务器,并向后端8080发送请求,由于端口不同,也是跨域请求
http://127.0.0.1:5500
http://127.0.0.1:8080
在springboot项目中,对于跨域请求默认会被拒绝访问,因此要启用跨域请求访问,后端服务器需要添加一些配置
这里以使用springboot2.0版本为例介绍以下几种配置方法
方式1:使用注解@CrossOrigin
Controller类上直接使用注解@CrossOrigin
而无需其他配置即可访问
@CrossOrigin
@RestController
@RequestMapping("/test")
public class TestController {
//
}
方式2:配置类中只需配置一个CorsFilter
即可实现
package com.developer.corstest.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
//看清楚,这里导入的包,不要错误导入:
//import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsWebFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许的请求头
corsConfiguration.addAllowedHeader("*");
// 允许的请求源 (如:http://localhost:8080)
corsConfiguration.addAllowedOrigin("*");
// 允许的请求方法 ==> GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
corsConfiguration.addAllowedMethod("*");
// URL 映射 (如: /admin/**)
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
方式3:扫描过滤器实现
创建过滤器,并在在启动类上使用@ServletComponentScan(basePackages = "com.developer.corstest.filters")
扫描过滤器所在的包
@WebFilter(urlPatterns = "/*")
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//获取初始化参数
Enumeration<String> initParams = filterConfig.getInitParameterNames();
System.out.println("filterConfig = " + filterConfig);
while(initParams.hasMoreElements()){
System.out.println(initParams.nextElement());
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("servletRequest = " + servletRequest + ", servletResponse = " + servletResponse + ", filterChain = " + filterChain);
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// Access-Control-Allow-Origin
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin") );
response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
方式4:配置类注册过滤器实现
创建一个继承于Filter的过滤器类,该过滤器上面不需要使用任何注解,然后将这个过滤器在配置类
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
//@Bean(name="corsFilter")
public FilterRegistrationBean filterRegistrationBean() {
//CORSFilter过滤器
FilterRegistrationBean registration = new FilterRegistrationBean(new CORSFilter());
// 过滤所有请求,/*可以匹配/xxx,/xxx/xxx,/xxxx/xxx...等
registration.addUrlPatterns("/*");
System.out.println("1.CORSFilterRegistration-----");
//如有需要,可设置初始化参数,在过滤器init方法中就能取到这些参数
registration.addInitParameter("paramName", "paramValue");
registration.setName("corsFilter");
//数字越小,优先级越高,对于当发送http请求时首先进入高优先级的过滤器
registration.setOrder(1);
return registration;
}
}
方式5:拦截器实现
(1)首先创建一个拦截器类,配置请求头参数
//拦截器
public class CorsInterceptor implements HandlerInterceptor {
/**
* 提供跨域支持,目标方法执行之前调用
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//跨域访问设置:response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//或者:httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
response.setHeader("Access-Control-Allow-Headers","*");
//或设置*
response.setHeader("Access-Control-Allow-Method","GET,POST,OPTIONS,PUT,DELETE");
//允许所有的域名跨域访问,使用 response.setHeader("Access-Control-Allow-Origin","*")通常无效,应该使用如下方式
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
System.out.println("Origin="+request.getHeader("Origin"));
System.out.println("uri="+request.getRequestURI());
System.out.println("url="+request.getRequestURL());
String token = request.getHeader("AUTHORIZATION");
System.out.println("token="+token);
/**
* 前端请求设置credentials: 'include', 这里就必须设置为true
* Response to preflight request doesn't pass access control check:
* The value of the 'Access-Control-Allow-Credentials' header in the response is '' which
* must be 'true' when the request's credentials mode is 'include'.
**/
response.setHeader("Access-Control-Allow-Credentials", "true");
// 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态
if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
response.setStatus(HttpStatus.OK.value());
return false;
}
return true;
}
}
(2)然后创建一个配置类实现WebMvcConfigurer
接口,并在addInterceptors()
方法中添加拦截器类
//springboot版本2.2.2.RELEASE
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("addInterceptors...");
registry.addInterceptor(new CorsInterceptor()).
addPathPatterns("/**").
excludePathPatterns("/static/**", "/error.html");
}
方式6:配置类覆盖接口方法
只需要覆盖以下方法即可实现,这是最简单的方法
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//配置允许跨域的路径
registry.addMapping("/**")
//配置允许访问的跨域资源的请求域名
.allowCredentials(true)
.allowedOrigins("*")
//配置允许访问该跨域资源服务器的请求方法
.allowedMethods("*")
//配置允许请求 头部head的访问
.allowedHeaders("*");
}
}