Java后端配置允許跨域方式
1. 使用 @CrossOrigin 注解 (Spring MVC)
如果你使用的是Spring MVC或Spring Boot,最簡單的方法是直接在控制器類或方法上使用@CrossOrigin注解來允許特定來源的跨域請求。
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") // 允許來自example.com的跨域請求
public class MyController {
@GetMapping("/api/data")
public String getData() {
return "Data from server";
}
}你可以指定多個來源,或者使用*來允許所有來源(但不推薦用于生產(chǎn)環(huán)境):
@CrossOrigin(origins = "*") // 允許所有來源
2. 配置全局 CORS 支持 (Spring Boot)
為了在整個應(yīng)用程序中統(tǒng)一配置CORS規(guī)則,而不是逐個控制器或方法進行配置,可以通過實現(xiàn)WebMvcConfigurer接口并在其中定義全局的CORS配置。
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 WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 應(yīng)用于所有路徑
.allowedOrigins("http://example.com") // 允許的來源
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允許的方法
.allowCredentials(true) // 是否允許發(fā)送憑證信息(如Cookies)
.maxAge(3600); // 預(yù)檢請求的有效期(秒)
}
};
}
}3. 使用 Spring Security 配置 CORS (如果使用了 Spring Security)
如果你的應(yīng)用程序使用了Spring Security,你還需要確保在安全配置中也啟用了CORS支持。
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().disable(); // 根據(jù)需要啟用或禁用CSRF保護
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://example.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}4. 手動設(shè)置響應(yīng)頭 (Servlet API)
對于不使用Spring框架的項目,可以在Servlet中手動設(shè)置響應(yīng)頭來允許跨域請求。
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 設(shè)置CORS響應(yīng)頭
response.setHeader("Access-Control-Allow-Origin", "http://example.com");
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");
// 處理預(yù)檢請求
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
// 正常處理請求
response.getWriter().print("Data from server");
}
}
}總結(jié)
根據(jù)你的技術(shù)棧和需求選擇最適合的方式來配置CORS。
無論是通過注解、全局配置還是手動設(shè)置響應(yīng)頭,關(guān)鍵是確保你正確地指定了允許的來源、方法和其他必要的參數(shù)。
如果你使用的是Spring框架,特別是Spring Boot,推薦使用@CrossOrigin注解或全局配置的方式,因為它們更簡潔且易于維護。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring?AOP?的實現(xiàn)和切點表達式的實現(xiàn)方式
本文給大家介紹了Spring?AOP的基本概念、通知類型、切點表達式和切面優(yōu)先級,并通過示例代碼展示了如何實現(xiàn)這些功能,感興趣的朋友跟隨小編一起看看吧2024-12-12
springboot集成nacos報錯:get data from Nacos
這篇文章給大家介紹了springboot集成nacos報錯:get data from Nacos error,dataId:null.yaml的原因及解決方法,如果又遇到相同問題的朋友可以參考閱讀本文2023-10-10
Java?+?Selenium?+?OpenCV解決自動化測試中的滑塊驗證問題
OpenCV是一個基于Apache2.0許可(開源)發(fā)行的跨平臺計算機視覺和機器學(xué)習(xí)軟件庫,可以運行在Linux、Windows、Android和Mac?OS操作系統(tǒng)上,這篇文章主要介紹了Java?+?Selenium?+?OpenCV解決自動化測試中的滑塊驗證,需要的朋友可以參考下2022-07-07

