一种基于spring拦截器的跨域解决方案

/**
 * @Description: 跨域支持(商旅有在拦截器阶段抛出异常,cross注解不能支持拦截器阶段的跨域,所以在登录拦截器之前先处理跨域支持)
 * @Date: 2018/3/7.
 */
public class CrossInterceptor extends HandlerInterceptorAdapter implements InitializingBean {
    private String accessControlAllowOrigin;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String curOrigin = request.getHeader("Origin");
        if (StringUtils.isNotBlank(curOrigin)) {
            String[] allowUrls = accessControlAllowOrigin.split(",");
            for (String origin : allowUrls) {
                if (origin.equals(curOrigin)) {
                    response.addHeader("Access-Control-Allow-Origin", origin);
                }
            }
        }
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie, Authorization");
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (StringUtils.isBlank(accessControlAllowOrigin)) {
            throw new RuntimeException("请配置CrossInterceptor跨域支持的host");
        }
    }

    public void setAccessControlAllowOrigin(String accessControlAllowOrigin) {
        this.accessControlAllowOrigin = accessControlAllowOrigin;
    }
}

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/"/>
        <mvc:mapping path="/**/*"/>
        <bean class="com.jd.ct.enterman.web.interceptor.CrossInterceptor">
            <property name="accessControlAllowOrigin" value="${cross.accessControlAllowOrigin}"></property>
        </bean>
    </mvc:interceptor>
</mvc:interceptors>
阅读更多
文章标签: 跨域
个人分类: 服务器
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭