之前写过通过注释的方法解决跨域请求的方法,需要每次都在controll类使用注解,这次通过springmvc的拦截器解决:

继承SpringMVC的类HandlerInterceptor重写preHandle方法,这个方法会在到达  controll之前调用,如下

public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Credentials","true"); //是否允许浏览器携带用户身份信息(cookie)
        return true;
    }

springmvc配置如下:

<mvc:interceptors >
	<!--过滤所有请求,处理跨域请求问题-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.jzy.interceptor.CommonInterceptor"></bean>
        </mvc:interceptor>
</mvc:interceptors >

这样既可解决SSM+VUE前后端分离时跨域请求的限制

Logo

前往低代码交流专区

更多推荐