15. 扩展: Spring Boot CORS支持

本文介绍了如何在SpringBootRESTfulWeb服务中启用CORS,包括在控制器方法中使用@CrossOrigin注解以及全局配置CORS支持,以允许来自特定源的跨域请求。
摘要由CSDN通过智能技术生成

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");
         }
      };
   }
}
  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我超爱写bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值