Java后端配置允許跨域方式
1. 使用 @CrossOrigin 注解 (Spring MVC)
如果你使用的是Spring MVC或Spring Boot,最簡(jiǎn)單的方法是直接在控制器類或方法上使用@CrossOrigin注解來(lái)允許特定來(lái)源的跨域請(qǐng)求。
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") // 允許來(lái)自example.com的跨域請(qǐng)求
public class MyController {
@GetMapping("/api/data")
public String getData() {
return "Data from server";
}
}你可以指定多個(gè)來(lái)源,或者使用*來(lái)允許所有來(lái)源(但不推薦用于生產(chǎn)環(huán)境):
@CrossOrigin(origins = "*") // 允許所有來(lái)源
2. 配置全局 CORS 支持 (Spring Boot)
為了在整個(gè)應(yīng)用程序中統(tǒng)一配置CORS規(guī)則,而不是逐個(gè)控制器或方法進(jìn)行配置,可以通過(guò)實(shí)現(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") // 允許的來(lái)源
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允許的方法
.allowCredentials(true) // 是否允許發(fā)送憑證信息(如Cookies)
.maxAge(3600); // 預(yù)檢請(qǐng)求的有效期(秒)
}
};
}
}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保護(hù)
}
@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. 手動(dòng)設(shè)置響應(yīng)頭 (Servlet API)
對(duì)于不使用Spring框架的項(xiàng)目,可以在Servlet中手動(dòng)設(shè)置響應(yīng)頭來(lái)允許跨域請(qǐ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ù)檢請(qǐng)求
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
// 正常處理請(qǐng)求
response.getWriter().print("Data from server");
}
}
}總結(jié)
根據(jù)你的技術(shù)棧和需求選擇最適合的方式來(lái)配置CORS。
無(wú)論是通過(guò)注解、全局配置還是手動(dòng)設(shè)置響應(yīng)頭,關(guān)鍵是確保你正確地指定了允許的來(lái)源、方法和其他必要的參數(shù)。
如果你使用的是Spring框架,特別是Spring Boot,推薦使用@CrossOrigin注解或全局配置的方式,因?yàn)樗鼈兏?jiǎn)潔且易于維護(hù)。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring?AOP?的實(shí)現(xiàn)和切點(diǎn)表達(dá)式的實(shí)現(xiàn)方式
本文給大家介紹了Spring?AOP的基本概念、通知類型、切點(diǎn)表達(dá)式和切面優(yōu)先級(jí),并通過(guò)示例代碼展示了如何實(shí)現(xiàn)這些功能,感興趣的朋友跟隨小編一起看看吧2024-12-12
springboot集成nacos報(bào)錯(cuò):get data from Nacos
這篇文章給大家介紹了springboot集成nacos報(bào)錯(cuò):get data from Nacos error,dataId:null.yaml的原因及解決方法,如果又遇到相同問(wèn)題的朋友可以參考閱讀本文2023-10-10
Java?+?Selenium?+?OpenCV解決自動(dòng)化測(cè)試中的滑塊驗(yàn)證問(wèn)題
OpenCV是一個(gè)基于Apache2.0許可(開(kāi)源)發(fā)行的跨平臺(tái)計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)軟件庫(kù),可以運(yùn)行在Linux、Windows、Android和Mac?OS操作系統(tǒng)上,這篇文章主要介紹了Java?+?Selenium?+?OpenCV解決自動(dòng)化測(cè)試中的滑塊驗(yàn)證,需要的朋友可以參考下2022-07-07
使用@Slf4j注解,log.info()無(wú)法使用問(wèn)題
在使用Lombok的@Slf4j注解打印日志時(shí)遇到問(wèn)題,通過(guò)降低Lombok版本(從1.18.x降至1.16.10)解決了問(wèn)題2024-12-12

