1、javaConfig方式
/**
* @author francis
* @version 2017/7/10.
*
* 下面2种方式,2选1都可以
*/
@Configuration
@EnableWebMvc
public class CrossConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false)
.maxAge(3600);
}
};
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
2、注解方式 @CrossOrigin
/**
* @author francis
* @version 2017/7/10.
*
* @CrossOrigin 可方法可类
*/
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class CrossController {
@GetMapping("/{id}")
public void retrieve(@PathVariable Long id) {
// ...todo
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...todo
}
}
3、Filter方式,新建Filter,在response里加上以下这些
/**
* @author francis
* @version 2017/7/10.
*/
public class CrossFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
res.addHeader("Access-Control-Allow-Origin", "http://domain2.com");
res.addHeader("Access-Control-Max-Age", "1800");
res.addHeader("Access-Control-Allow-Credentials", "true");
}
@Override
public void destroy() {
}
}