1. 第一種
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author Mcally
* @time
* @des 跨越解決方式
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMAppings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
這種方式是全局配置的,網上也大都是這種解決辦法,但是很多都是基于舊的spring版本,比如 WebMvcConfigurerAdapter 在spring5.0已經被標記為Deprecated,點開源碼可以看到:
/**
* An implementation of {@link WebMvcConfigurer} with empty methods allowing
* subclasses to override only the methods they're interested in.
*
* @author Rossen Stoyanchev
* @since 3.1
* @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
* possible by a JAVA 8 baseline) and can be implemented directly without the
* need for this adapter
*/
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}
2.第二種
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Mcally
* @time
* @des 跨越解決方式
*/
@WebFilter(filterName = "CorsFilter")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}
這種辦法,是基于過濾器的方式,方式簡單明了,就是在response中寫入這些響應頭,好多文章都是第一種和第二種方式都叫你配置,其實這是沒有必要的,只需要一種即可。
3.第三種
/**
* @author Mcally
* @time
* @des 跨越解決方式
*/
public class HelloController {
@CrossOrigin(origins = "http://localhost:4000")
@GetMapping("goods-url")
public Response hello(@RequestParam String url) throws Exception {}
}
沒錯就是@CrossOrigin注解,點開注解元注解@Target可以看出,注解可以放在method、class等上面,類似RequestMapping,也就是說,整個controller下面的方法可以都受控制,也可以單個方法受控制。
也可以得知,這個是最小粒度的cors控制辦法了,精確到單個請求級別。
注
以上三種方法都可以解決問題,最常用的應該是第一種、第二種,控制在自家幾個域名范圍下足以,一般沒必要搞得太細。
這三種配置方式都用了的話,誰生效呢,類似css中樣式,就近原則,懂了吧。