java前后端分离后台解决跨域问题

一般解决跨域问题的方案有两种,jsonp以及cors。因为jsonp需要前后台做配合统一标示个人感觉比较麻烦,所以本人选择使用cors方案来解决此问题。





    
    
    Title
    
    


    
{{ message }}
{{ data.code }}

后台用的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() {

    }
}
  
    crossFilter
    com.hxl.site.modules.test.filter.CrossFilter
  

  
    crossFilter
    /*
  

二 使用切面

代码里的注释打开

/**
 * 后台解决跨域问题
 */
//@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;
    }

}

你可能感兴趣的:(springMVC,spring)