跨域一直是一个令人头疼的问题,对于初学者而言可能觉得本地测试接口都没有问题,为什么部署到线上就出现bug了,完全没有头脑。对于前端 VUE 开发者而言,后台不处理,基本就会出现跨域问题。而处理跨域问题的方案也是八仙过海,各显神通。本文将介绍在 Spring Boot 项目中一种相对传统的方法,通过拦截器的方式彻底解决跨域问题。
(PS: 在文末参考资料中也有使用 Spring 框架自带的跨域问题解决方案)
SpringBoot 启动类
../demo-web/src/main/java/com/ljq/demo/springboot/web/DemoWebApplication.java package com.ljq.demo.springboot.web; import com.ljq.demo.springboot.web.acpect.SimpleCORSFilter; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @EnableEurekaServer @ComponentScan(basePackages = {"com.ljq.demo"}) @MapperScan("com.ljq.demo.springboot.dao") @ServletComponentScan @EnableCaching public class DemoWebApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(DemoWebApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(DemoWebApplication.class); } /** * 跨域处理 * * @return */ @Bean public SimpleCORSFilter simpleCORSFilter(){ return new SimpleCORSFilter(); } }
Java CORS Filter Example
Spring CORS – Spring @CrossOrigin example
CORS with Spring
Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo
个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
