在Java后端實現跨域配置(CORS,Cross-Origin Resource Sharing)有多種方法,具體取決于你使用的框架。如果你使用的是Spring Boot或Spring MVC,可以通過以下幾種方式來配置CORS。
?
### 方法一:全局配置
?
對于所有請求的跨域配置,可以在Spring Boot應用中通過`WebMvcConfigurer`接口進行全局配置:
?
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
?
@Configuration
public class CorsConfig {
?
? ? @Bean
? ? public WebMvcConfigurer corsConfigurer() {
? ? ? ? return new WebMvcConfigurer() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void addCorsMappings(CorsRegistry registry) {
? ? ? ? ? ? ? ? registry.addMapping("/**") // 允許所有的路徑
? ? ? ? ? ? ? ? ? ? .allowedOrigins("*") // 允許所有的來源
? ? ? ? ? ? ? ? ? ? .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允許的方法
? ? ? ? ? ? ? ? ? ? .allowedHeaders("*") // 允許的頭部信息
? ? ? ? ? ? ? ? ? ? .allowCredentials(true); // 是否允許發送Cookie
? ? ? ? ? ? }
? ? ? ? };
? ? }
}
```
?
### 方法二:基于注解的方式
?
對于特定控制器或方法級別的跨域配置,可以使用`@CrossOrigin`注解:
?
```java
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
?
@RestController
@CrossOrigin(origins = "http://example.com") // 指定允許的來源
public class MyController {
?
? ? @GetMapping("/api/test")
? ? public String test() {
? ? ? ? return "Hello, CORS!";
? ? }
}
```
?
### 方法三:通過過濾器實現
?
如果需要更細粒度的控制,或者你需要對所有進入應用程序的請求都添加CORS響應頭,你可以創建一個自定義過濾器:
?
```java
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
?
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
?
@Configuration
public class CorsFilterConfig {
?
? ? @Bean
? ? public Filter corsFilter() {
? ? ? ? return new Filter() {
? ? ? ? ? ? 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", "POST, GET, OPTIONS, DELETE");
? ? ? ? ? ? ? ? response.setHeader("Access-Control-Max-Age", "3600");
? ? ? ? ? ? ? ? response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
?
? ? ? ? ? ? ? ? if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
? ? ? ? ? ? ? ? ? ? response.setStatus(HttpServletResponse.SC_OK);
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? chain.doFilter(req, res);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
?
? ? ? ? ? ? public void init(FilterConfig filterConfig) {}
?
? ? ? ? ? ? public void destroy() {}
? ? ? ? };
? ? }
}
```
?
以上三種方法可以根據你的需求選擇最適合的一種或組合使用。全局配置適用于大多數場景,而基于注解的方式則提供了更加精細的控制。過濾器提供了一種更底層的方式來處理跨域問題,并且可以在其他方面增強安全性或功能性。