跨域问题的解决,前端访问不了接口(前端和后台在不同的服务器)

package com.runmin.bajie.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AccessInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credential", "true");
        response.setHeader("P3P", "CP=CAO PSA OUR");
        if(request.getHeader("Access-Control-Request-Method")!=null&&"OPTIONS".equals(request.getMethod())) {
            response.addHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept");
            response.addHeader("Access-Control-Max-age", "120");

        }
        return true;
    }
    
}
    <!-- 5.跨域拦截器 -->    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*/**"/>
            <bean class="com.runmin.bajie.intercepter.AccessInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

在MVC配置文件中配置如上即可。

posted @ 2017-11-16 14:49  虚极静笃  Views(12151)  Comments(0Edit  收藏  举报