15. 扩展: Spring Boot CORS支持

Spring Boot CORS支持

跨源资源共享(CORS)是一种安全概念,用于限制Web浏览器中实现的资源。 它可以防止JavaScript代码产生或消耗针对不同来源的请求。

例如,Web应用程序在8080端口上运行,并且使用JavaScript尝试从9090端口使用RESTful Web服务。在这种情况下,在Web浏览器上将面临跨源资源共享安全问题。

处理此问题需要两个要求 -

  • RESTful Web服务应该支持跨源资源共享。
  • RESTful Web服务应用程序应允许从8080端口访问API。

在本章中,将详细了解如何为RESTful Web服务应用程序启用跨源请求。

在控制器方法中启用CORS

需要通过对控制器方法使用@CrossOrigin注解来设置RESTful Web服务的起源。 @CrossOrigin注源支持特定的REST API,而不支持整个应用程序。

复制代码
@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {
   return null;
}
全局CORS配置

需要定义显示的@Bean配置,以便为Spring Boot应用程序全局设置CORS配置支持。

复制代码
@Bean
public WebMvcConfigurer corsConfigurer() {
   return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/products").allowedOrigins("http://localhost:9000");
      }    
   };
}

下面给出了在主Spring Boot应用程序中全局设置CORS配置的代码。

复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/products").allowedOrigins("http://localhost:8080");
         }
      };
   }
}
相关推荐
uzong14 分钟前
Harness Engineering 是什么?一场新的 AI 范式已经开始
人工智能·后端·架构
2401_8512729926 分钟前
自定义内存检测工具
开发语言·c++·算法
章鱼丸-37 分钟前
DAY31 文件的拆分和写法
开发语言·python
左左右右左右摇晃44 分钟前
Java并发——synchronized锁
java·开发语言
☆5661 小时前
C++中的命令模式
开发语言·c++·算法
唐叔在学习1 小时前
Python桌面端应用最小化托盘开发实践
后端·python·程序员
wenlonglanying1 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
yuhaiqiang1 小时前
被 AI 忽悠后,开始怀念搜索引擎了?
前端·后端·面试
CQU_JIAKE1 小时前
3.21【A】
开发语言·php
今儿敲了吗1 小时前
python基础学习笔记第九章——模块、包
开发语言·python