zoukankan      html  css  js  c++  java
  • 跨域问题的解决,前端访问不了接口(前端和后台在不同的服务器)

    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配置文件中配置如上即可。

  • 相关阅读:
    Django同步数据库(/manage.py makemigrations) 报错
    python中global和nonlocal用法的详细说明
    linux系统下载pycharm
    第一次博客作业
    结对编程作业
    团队介绍与选题报告
    FTP的时间为什么比系统时间晚了八个小时?
    新的部落格
    Enter键提交表单
    Android动画RotateAnimation(fromDegrees, toDegrees, pivotX,pivotY)参数
  • 原文地址:https://www.cnblogs.com/XJJD/p/7844331.html
Copyright © 2011-2022 走看看