前后端分離開發中,跨域問題是很常見的一種問題。本文主要是解決 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() {
}
}
再看前端訪問結果,已經可以正常訪問了:

