Spring Boot 教程:CORS 支持

【注】本文译自: https://www.tutorialspoint.com/spring_boot/spring_boot_cors_support.htm

  跨域资源共享 (CORS) 是一个安全概念,它允许在 web 浏览器中实现对资源访问的限制。它可避免 JavaScript 代码产生或消费别跨越不同域的请求。
  例如,你的运行在 8080 端口的 web 应用试图使用 JavaScript 消费来自 9090 端口的 RESTful web 服务。在这样的情形下,你将面对 web 浏览器上跨域资源共享的安全问题。
  这个问题有两个需求要处理:

  • RESTful web 服务应当支持跨域资源共享。
  • RESTful web 服务应用应当允许来自 8080 端口访问 API(s)。
      在本文中,我们将详细学习如何让一个 RESTful Web 服务应用能够进行跨域请求。

在控制器方法中赋能 CORS

  我们需要在控制器方法上对一个 RESTful web 服务使用 @CrossOrigin 设置源。@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 的代码如下:

package com.tutorialspoint.demo;

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");
         }
      };
   }
}

  现在,你创建了一个 Spring Boot web 应用,运行在 8080 端口上,RESTful web 服务应用运行在 9090 端口上。关于如何实现 RESTful Web 服务,你可以参考本系列教程的另外一部分:消费 RESTful Web 服务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值