前后端分离开发中,跨域问题是很常见的一种问题。本文主要是解决 springboot
项目跨域访问的一种方法,其他 javaweb
项目也可参考。
1.首先要了解什么是跨域
由于前后端分离开发中前端页面与后台在不同的服务器上,必定会出现跨区问题。关于更具体的信息,可以看这里:
2.springboot中通过配置Filter来解决跨域问题
2-1.首先看一下会出现跨域问题的代码:
前端代码:
Insert title here Test
出现了跨域问题:
后端代码:
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;@RestController@RequestMapping(value = "/example")public class CrosTestController { @GetMapping(value = "/testget") public MaptestGet(){ Map testMap = new HashMap<>(); testMap.put("name", "jack"); //用来打印验证后端代码确实执行了,即该接口确实被访问了 System.out.println("执行了!"); return testMap; }}
2-2.解决问题:
无需改动前端代码,在 springboot
项目中添加全局过滤器:
import com.example.filter.CrosFilter;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class exampleApplication { public static void main(String[] args) { SpringApplication.run(exampleApplication.class, args); } /** * 配置跨域访问的过滤器 * @return */ @Bean public FilterRegistrationBean registerFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.addUrlPatterns("/*"); bean.setFilter(new CrosFilter()); return bean; }}
过滤器:
import javax.servlet.*;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class CrosFilter implements javax.servlet.Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) servletResponse; //*号表示对所有请求都允许跨域访问 res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { }}
再看前端访问结果,已经可以正常访问了: