spring boot + cors解决前后端跨域问题

前后端分离部署技术大体有几种:jsonp,CORS,nginx反向代理,其中jsonp不支持post方法,具体说下CORS技术。

前端请求代码不变,用jquery.ajax()去请求

$.ajax({
    		url:"http://127.0.0.1:8080/user/login",
			type:'post',
			dataType : 'json',
		 	data:params,
		 	contentType : "application/json",
		 	success:function(date){
		 		dispalyLoad();
			  if(date==0){
				  location.href="user/action.html";
			  }else if(date==1){
				  alert("账号错误");
			  }else if(date==2){
				  alert("密码错误");
			  }
		  }
    }); 

后端我用的是spring boot  ,实现解决跨域问题主要有两种实现

第一种,用Filter拦截器进行对HttpServletResponse增加header,具体代码如下:

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "allFilter")
public class CORSFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse res = (HttpServletResponse) response;
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setHeader("Access-Control-Allow-Methods", "*");
		res.setHeader("Access-Control-Max-Age", "1728000");
		res.setHeader("Access-Control-Allow-Credentials", "true");
		res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(request, res);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}

和spring mvc增加filter最大的区别就是spring boot提供了两个注解@ServletComponentScan @WebFilter省去了配置web.xml的麻烦,这样直接启动然后调用就可以实现前后端跨域了。

第二种办法就是增加一个aop切面,对所有的controller进行切面编程,从而增加header

先增加spring boot的aop依赖

<dependency>
        	<groupId>org.springframework.boot</groupId>
        	<artifactId>spring-boot-starter-aop</artifactId>
    	</dependency>

然后再写一个aop类,在头部插入Access-Control-Allow-Origin

public class ControllerAop {
	
	@Around("execution (* com.xx.controller.*.*(..))")
	public Object CORSAop(ProceedingJoinPoint pjp) throws Throwable{
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT");
        Object proceed = pjp.proceed();
        return proceed;
	}

这样就可以实现前后端跨域了

posted @ 2018-05-16 14:52  luoylove  阅读(663)  评论(0编辑  收藏  举报