美文网首页
springboot 允许跨域

springboot 允许跨域

作者: minusplus | 来源:发表于2019-08-25 21:18 被阅读0次

    设置跨域拦截器

    1. 在拦截器包下创建跨域拦截器
    /**
     * 跨域拦截器
     */
    @Component
    public class CROSInterceptor implements HandlerInterceptor {
        /**
         * 进入controller层之前拦截请求
         * @param httpServletRequest
         * @param httpServletResponse
         * @param o
         * @return
         * @throws Exception
         */
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            Object host = httpServletRequest.getHeader("host");
            String origin = httpServletRequest.getHeader("Origin");
            if (origin == null){
                return true;
            }
            httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
            //httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");填写*号,delete等好像不可用
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS,PATCH");
            httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin,Content-Type,Accept,token,X-Requested-With");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            System.out.println("---------------------开始进入请求地址拦截----------------------------"+host+"==="+origin);
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    //        System.out.println("--------------处理请求完成后视图渲染之前的处理操作---------------");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    //        System.out.println("---------------视图渲染之后的操作-------------------------0");
        }
    
    }
    
    1. 注册拦截器 全局使用
    /**
     * 注册拦截器
     */
    @Configuration
    public class WebAppConfig implements WebMvcConfigurer {
        @Autowired
        private CROSInterceptor crosInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(crosInterceptor).addPathPatterns("/**");
        }
    }
    
    1. 项目结构


      在这里插入图片描述

    相关文章

      网友评论

          本文标题:springboot 允许跨域

          本文链接:https://www.haomeiwen.com/subject/soikectx.html