国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

SpringBoot 如何解決跨域問題?

2023-08-30 15:17 作者:程序員的勇敢  | 我要投稿

跨域問題應(yīng)該是我們?nèi)粘i_發(fā)中比較常見的,在Spring Boot應(yīng)用中,通常解決跨域問題(Cross-Origin Resource Sharing,CORS)有如下四種方法:

1. 使用 @CrossOrigin 注解

在Controller類或方法上使用@CrossOrigin注解可以很容易地解決跨域問題。這是最簡單和最直接的方法。

?@RestController
?@CrossOrigin(origins?=?"http://example.com")?// 允許該域名的跨域訪問
?public?class?MyController?{
?
??? ?@GetMapping("/some-resource")
??? ?public?String?someResource() {
??? ? ? ?return?"Hello, World!";
??? }
?}

2. 全局CORS配置

可以在Spring Boot應(yīng)用中添加全局CORS配置。這通常通過實現(xiàn)WebMvcConfigurer接口完成。

?@Configuration
?public?class?WebConfig?implements?WebMvcConfigurer?{
?
??? ?@Override
??? ?public?void?addCorsMappings(CorsRegistry?registry) {
??? ? ? ?registry.addMapping("/**") ?// 對所有路徑應(yīng)用CORS配置
??? ? ? ? ? .allowedOrigins("http://example.com")
??? ? ? ? ? .allowedMethods("GET",?"POST",?"PUT",?"DELETE")
??? ? ? ? ? .allowedHeaders("Header1",?"Header2",?"Header3")
??? ? ? ? ? .exposedHeaders("Header1",?"Header2")
??? ? ? ? ? .allowCredentials(true).maxAge(3600);
??? }
?}

3. 使用 CorsFilter

除了使用@CrossOrigin和全局配置,還可以通過自定義CorsFilter來解決跨域問題。

?@Configuration
?public?class?MyConfiguration?{
?
??? ?@Bean
??? ?public?CorsFilter?corsFilter() {
??? ? ? ?UrlBasedCorsConfigurationSource?source?=?new?UrlBasedCorsConfigurationSource();
??? ? ? ?CorsConfiguration?config?=?new?CorsConfiguration();
??? ? ? ?config.addAllowedOrigin("http://example.com");
??? ? ? ?config.addAllowedHeader("*");
??? ? ? ?config.addAllowedMethod("*");
??? ? ? ?source.registerCorsConfiguration("/**",?config);
??? ? ? ?return?new?CorsFilter(source);
??? }
?}

4. 使用 @ControllerAdvice@ModelAttribute

在某些情況下,你也可以使用@ControllerAdvice@ModelAttribute來全局處理請求和響應(yīng),從而手動設(shè)置CORS相關(guān)的HTTP頭。

?@ControllerAdvice
?public?class?GlobalAdvice?{
?
??? ?@ModelAttribute
??? ?public?void?setCORSHeaders(HttpServletResponse?response) {
??? ? ? ?response.setHeader("Access-Control-Allow-Origin",?"http://example.com");
??? ? ? ?// 其他CORS相關(guān)設(shè)置
??? }
?}


SpringBoot 如何解決跨域問題?的評論 (共 條)

分享到微博請遵守國家法律
民乐县| 富民县| 塘沽区| 景德镇市| 师宗县| 河东区| 冷水江市| 镇安县| 清丰县| 油尖旺区| 宁海县| 广州市| 武清区| 泽州县| 会昌县| 四平市| 尉氏县| 怀集县| 大厂| 罗定市| 文安县| 兴海县| 洪雅县| 阳谷县| 应用必备| 天等县| 海伦市| 桐庐县| 宝丰县| 武清区| 杭锦后旗| 定安县| 丰台区| 阿鲁科尔沁旗| 宁德市| 奉贤区| 石林| 枝江市| 西乡县| 吉林省| 荣成市|