java前后端分离后台解决跨域问题
Posted java-北京-菜鸟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java前后端分离后台解决跨域问题相关的知识,希望对你有一定的参考价值。
一般解决跨域问题的方案有两种,jsonp以及cors。因为jsonp需要前后台做配合统一标示个人感觉比较麻烦,所以本人选择使用cors方案来解决此问题。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Access-Control-Allow-Origin" content="*" />
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="app">
message
</div>
<div id="ajax1">
data.code
</div>
<script type="text/javascript">
var app = new Vue(
el: '#app',
data:
message: 'Hello Vue!'
);
new Vue(
el:'#ajax1',
data:data:"",
beforeCreate:function()
var url="http://192.168.0.190:8089/test/testJson";
var _self=this;
$.get(url,function(data)
_self.data=eval("(" + data +")");
console.log(_self.data.code);
)
);
</script>
</body>
</html>
后台用的springmvc,方法是在controller之前设置一下
一, 使用filter
/**
* filter解决跨域问题
*/
@Component
public class CrossFilter implements Filter
@Override
public void init(FilterConfig filterConfig) throws ServletException
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
System.out.println("this is cross filter");
HttpServletResponse response = (HttpServletResponse) res;
//如果要做细的限制,仅限某域名下的可以进行跨域访问到此,可以将*改为对应的域名。
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "1728000");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
@Override
public void destroy()
<filter>
<filter-name>crossFilter</filter-name>
<filter-class>com.hxl.site.modules.test.filter.CrossFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>crossFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
二 使用切面
代码里的注释打开
/**
* 后台解决跨域问题
*/
//@Configuration
//@Aspect
public class ControllerAOP
// @Around("execution (* com.hxl.site.modules..*.controller..*.*(..))")
public Object testAop(ProceedingJoinPoint pro) throws Throwable
System.out.println("=====================");
//获取response
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//核心设置
response.setHeader("Access-Control-Allow-Origin", "*");
//执行调用的方法
Object proceed = pro.proceed();
return proceed;
以上是关于java前后端分离后台解决跨域问题的主要内容,如果未能解决你的问题,请参考以下文章