springBoot处理跨域
基于spring boot 2.3.0.RELEASE 版本的跨域处理方案
https://blog.csdn.net/weixin_45083630/article/details/132342539
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
缺什么响应头就返回什么响应头就可以了
方式一
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author JHL
*/
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 设置预检请求的有效期,有效期内不会重复预检
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
// 跨域标识
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
// 指示服务器允许客户端在跨域请求的实际请求中携带的自定义请求头
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
// 处理预检请求(OPTIONS请求)
if ("OPTIONS".equals(request.getMethod())) {
response.getWriter().println("ok");
return;
}
chain.doFilter(servletRequest, servletResponse);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
方式二
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 跨域配置
* @author JHL
* @version 1.0
* @since : JDK 11
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// config.addAllowedOriginPattern("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
方式三
使用@CrossOrigin
注解标注控制层类或者方法实现跨域
org.springframework.boot:2.3.0.RELEASE
可以直接用