SpringBoot项目中实现跨域的解决方案

}

}

3、使用注解(局部跨域)

在方法上(@RequestMapping)使用注解 @CrossOrigin :

package com.riemann.springbootdemo.common.cors;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

/**

  • @author riemann

  • @date 2019/08/26 23:16

*/

// 2、在方法上注解

@Controller

public class MethodAnnotationCors {

@RequestMapping(“/hello”)

@ResponseBody

@CrossOrigin(“http://localhost:8080”)

public String index( ){

return “Hello World”;

}

}

或者在控制器(@Controller)上使用注解 @CrossOrigin :

package com.riemann.springbootdemo.common.cors;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.CrossOri 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 gin;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

/**

  • @author riemann

  • @date 2019/08/26 23:13

*/

// 1、在控制器上注解

@Controller

@CrossOrigin(origins = “http://xx-domain.com”, maxAge = 3600)

public class ControllerAnnotationCors {

@RequestMapping(“/hello”)

@ResponseBody

public String index( ){

return “Hello World”;

}

}

4、手工设置响应头(局部跨域 )

使用HttpServletResponse对象添加响应头(Access-Control-Allow-Origin)来授权原始域,这里Origin的值也可以设置为"*" ,表示全部放行。

package com.riemann.springbootdemo.common.cors;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**

  • @author riemann

  • @date 2019/08/26 23:21

*/

// 第四种方式:手工设置响应头(局部跨域)

public class ManualSettingCors {

@RequestMapping(“/hello”)

@ResponseBody

public String index(HttpServletResponse response){

response.addHeader(“Access-Control-Allow-Origin”, “http://localhost:8080”);

return “Hello World”;

}

}

[](()四、测试跨域访问


首先使用 Spring Initializr 快速构建一个Maven工程,什么都不用改,在static目录下,添加一个页面:index.html 来模拟跨域访问。目标地址: http://localhost:8090/hello

Page Index

前台系统

然后创建另一个工程,在Root Package添加Config目录并创建配置类来开启全局CORS。

@Configuration

public class GlobalCorsConfig {

@Bean

public WebMvcConfigurer corsConfigurer() {

return new WebMvcConfigurer() {

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping(“/**”);

}

};

}

}

接着,简单编写一个Rest接口 ,并指定应用端口为8090。

@SpringBootApplication

@RestController

public class YyWebApplication {

@Bean

public TomcatServletWebServerFactory tomcat() {

TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();

tomcatFactory.setPort(8090); //默认启动8090端口

return tomcatFactory;

}

@RequestMapping(“/hello”)

public String index() {

return “Hello World”;

}

你可能感兴趣的:(Java,经验分享,架构,java)