×
Spring Boot教程Spring Boot简介Spring Boot快速入门Spring Boot引导过程Spring Boot Tomcat部署Spring Boot构建系统Spring Boot代码结构Spring Boot Bean和依赖注入Spring Boot运行器(Runner)Spring Boot应用程序属性Spring Boot日志Spring Boot构建RESTful Web服务Spring Boot异常处理Spring Boot拦截器Spring Boot Servlet过滤器Spring Boot Tomcat端口号Spring Boot Rest模板Spring Boot文件处理Spring Boot服务组件Spring Boot Thymeleaf示例Spring Boot使用RESTful Web服务Spring Boot CORS支持Spring Boot国际化Spring Boot调度Spring Boot启用HTTPSSpring Boot Eureka服务器Spring Boost Eureka服务注册Spring Boot Zuul代理服务器和路由Spring Boot云配置服务器Spring Boot云配置客户端Spring Boot ActuatorSpring Boot管理服务器Spring Boot管理客户端Spring Boot启用Swagger2Spring Boot创建Docker镜像Spring Boot跟踪微服务日志Spring Boot Flyway数据库Spring Boot发送电子邮件Spring Boot HystrixSpring Boot Web SocketSpring Boot批量服务Spring Boot Apache KafkaSpring Boot单元测试用例Spring Boot Rest控制器单元测试Spring Boot数据库源(连接数据库)Spring Boot保护Web应用程序

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配置的代码。

package com.yiibai.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");
         }
      };
   }
}

现在,可以创建一个在8080端口上运行的Spring Boot Web应用程序和在9090端口上运行的RESTful Web服务应用程序。 有关RESTful Web Service实现的更多详细信息,请参阅本教程的“使用RESTful Web服务”一章。


分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)