zoukankan      html  css  js  c++  java
  • CORS 跨域访问 后端代码

    使用拦截器去做跨域访问

    在验证时,需要在header里面传入token和userId来进行验证,所以需要特别注意的就是要在代码中将这两个参数加入,否则会出现异常

    package com.xw.interceptor;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author 12561
     */
    public class CrossDomainInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            response.addHeader("Access-Control-Allow-Origin","*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization,userId,token");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
        }
    
        /**
         * @param request
         * @param response
         * @param handler  拦截的对象
         * @param ex
         * @throws Exception
         */
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
        }
    }
    <mvc:interceptors>
            <!--登录拦截器-->
            <mvc:interceptor>
                <!-- 需拦截的地址 -->
                <!-- 拦截所有/manage -->
                <mvc:mapping path="/manage/**" />
    
                <!--登录和退出登录的方法不需要拦截-->
                <mvc:exclude-mapping path="/manage/user/tologin"/>
                <mvc:exclude-mapping path="/manage/user/login"/>
                <mvc:exclude-mapping path="/manage/user/exit"/>
                <bean class="com.xw.interceptor.LoginInterceptor"/>
            </mvc:interceptor>
    
            <!--跨域拦截器-->
            <mvc:interceptor>
                <!-- 需拦截的地址 -->
                <mvc:mapping path="/api*/**" />
                <bean class="com.xw.interceptor.CrossDomainInterceptor"/>
            </mvc:interceptor>
    
        </mvc:interceptors>

    拦截的是所有以api开头的接口,设置完之后就完成啦

  • 相关阅读:
    springmvc常用注解之@Controller和@RequestMapping
    解决nginx负载均衡的session共享问题
    iOS顶部滑动菜单:FDSlideBar 与NinaPagerView
    C#中使用WeiFenLuo.WinFormsUI.Docking.dll实现窗口停靠效果
    [转]C#使用Log4Net记录日志
    ICSharpCode.SharpZipLib 开源压缩库使用示例
    WorldWind源码剖析系列:日志类Log
    [转]反射基础
    WorldWind源码剖析系列:星球球体的加载与渲染
    Vue 前端路由 vue-router
  • 原文地址:https://www.cnblogs.com/SeaWxx/p/10178691.html
Copyright © 2011-2022 走看看