前后端分离开发中,跨域问题是很常见的一种问题。本文主要是解决 springboot
项目跨域访问的一种方法,其他 javaweb
项目也可参考。
1.首先要了解什么是跨域
由于前后端分离开发中前端页面与后台在不同的服务器上,必定会出现跨区问题。关于更具体的信息,可以看这里:不要再问我跨域的问题了
2.springboot中通过配置Filter来解决跨域问题
2-1.首先看一下会出现跨域问题的代码:
前端代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/vendor/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(function(){ $("a").click(function(){ var url = 'http://127.0.0.1:8080/example/testget'; var args = {"time" : new Date()}; //get请求 $.get(url, args, function(data){ alert(data); }); //禁止页面跳转 return false; }); }); </script> </head> <body> <h1>Test</h1> <li><a href="">click</a></li> </body> </html>
出现了跨域问题:
后端代码:
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 Map<String, String> testGet(){ Map<String, String> 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; @SpringBootApplication public 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() { } }
再看前端访问结果,已经可以正常访问了: