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"; } }
你可以指定多個來源,或者使用*
來允許所有來源(但不推薦用于生產環(huán)境):
@CrossOrigin(origins = "*") // 允許所有來源
2. 配置全局 CORS 支持 (Spring Boot)
為了在整個應用程序中統(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("/**") // 應用于所有路徑 .allowedOrigins("http://example.com") // 允許的來源 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允許的方法 .allowCredentials(true) // 是否允許發(fā)送憑證信息(如Cookies) .maxAge(3600); // 預檢請求的有效期(秒) } }; } }
3. 使用 Spring Security 配置 CORS (如果使用了 Spring Security)
如果你的應用程序使用了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. 手動設置響應頭 (Servlet API)
對于不使用Spring框架的項目,可以在Servlet中手動設置響應頭來允許跨域請求。
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 { // 設置CORS響應頭 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"); // 處理預檢請求 if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { // 正常處理請求 response.getWriter().print("Data from server"); } } }
總結
根據(jù)你的技術棧和需求選擇最適合的方式來配置CORS。
無論是通過注解、全局配置還是手動設置響應頭,關鍵是確保你正確地指定了允許的來源、方法和其他必要的參數(shù)。
如果你使用的是Spring框架,特別是Spring Boot,推薦使用@CrossOrigin
注解或全局配置的方式,因為它們更簡潔且易于維護。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
idea安裝jerbel及文件上傳下載的實現(xiàn)示例
JRebel是一個Java開發(fā)工具,它是一款用于實時代碼重載的插件,本文主要介紹了idea安裝jerbel及文件上傳下載的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解下2023-09-09Python基礎之如何使用multiprocessing模塊
今天帶大家學習python多進程的相關知識,文中對multiprocessing模塊的使用作了非常詳細的介紹,需要的朋友可以參考下2021-06-06使用Spring AntPathMatcher的doMatch方法
這篇文章主要介紹了使用Spring AntPathMatcher的doMatch方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09