springboot跨域
时间: 2023-09-21 10:05:34 浏览: 89
在Spring Boot中,可以通过配置Spring的CORS(跨域资源共享)支持来实现跨域请求。以下是实现跨域请求的步骤:
1. 添加CORS配置类
创建一个CORS配置类,添加@Configuation注解和@EnableWebMvc注解。在配置类中,使用addMapping方法配置允许跨域的请求路径和允许跨域的源。还可以配置其他CORS参数,如允许的请求方法、允许的请求头等。
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
2. 添加过滤器
创建一个CORS过滤器,实现javax.servlet.Filter接口。在过滤器中,使用HttpServletResponse的setHeader方法设置Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers、Access-Control-Allow-Credentials等响应头。
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-Custom-Header, X-Another-Header");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(request, response);
}
}
3. 注册过滤器
在Spring Boot的配置类中,使用@Bean注解将CORS过滤器注册到容器中。
@Configuration
public class AppConfig {
@Bean
public FilterRegistrationBean corsFilterRegistration() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CorsFilter());
registrationBean.setName("CORS Filter");
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(1);
return registrationBean;
}
}
以上是Spring Boot实现跨域请求的步骤。通过配置CORS支持和注册CORS过滤器,可以轻松地实现跨域请求。
阅读全文