// 剑气纵横九万里,一剑光寒九百州!
// CrossOrigin 注解
package com.huifer.source.controller;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@CrossOrigin(maxAge = 3600)
@RequestMapping("/")
@RestController
public class JSONController {
    @ResponseBody
    @GetMapping(value = "/json")
    public Object ob() {
//哈希重构    
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("1", "a");
        return hashMap;
    }
}

/**
         * controller 相关处理技巧
         *
         * @param mapping 请求地址
         * @param handler 处理类
         * @param method  函数
         */
        public void register(T mapping, Object handler, Method method) {
            // 上锁
            this.readWriteLock.writeLock().lock();
            try {
                // 创建 HandlerMethod , 通过 handler 创建处理的对象(controller)
                HandlerMethod handlerMethod = createHandlerMethod(handler, method);
                assertUniqueMethodMapping(handlerMethod, mapping);
                // 设置值
                this.mappingLookup.put(mapping, handlerMethod);

// 获取url
                List<String> directUrls = getDirectUrls(mapping);
                for (String url : directUrls) {
                    // 设置
                    this.urlLookup.add(url, mapping);
                }

String name = null;
                if (getNamingStrategy() != null) {
                    name = getNamingStrategy().getName(handlerMethod, mapping);
                    addMappingName(name, handlerMethod);
                }

/**
                 * 跨域设置
                 * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#initCorsConfiguration(Object, Method, RequestMappingInfo)}
                 **/
                CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
                if (corsConfig != null) {
                    this.corsLookup.put(handlerMethod, corsConfig);
                }

this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name));
            }
            finally {
                // 开锁
                this.readWriteLock.writeLock().unlock();
            }
        }
        
    @Override
    protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
        // 重新创建,为什么不作为参数传递: 还有别的实现方法
        HandlerMethod handlerMethod = createHandlerMethod(handler, method);
        // 获取bean
        Class<?> beanType = handlerMethod.getBeanType();

// 获取注解信息
        CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
        CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);

if (typeAnnotation == null && methodAnnotation == null) {
            return null;
        }

CorsConfiguration config = new CorsConfiguration();
        // 更新跨域信息
        updateCorsConfig(config, typeAnnotation);
        updateCorsConfig(config, methodAnnotation);

if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
            for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
                config.addAllowedMethod(allowedMethod.name());
            }
        }
        // 返回跨域配置默认值
        return config.applyPermitDefaultValues();
    }
    
    //CorsConfig 配置
      private void updateCorsConfig(CorsConfiguration config, @Nullable CrossOrigin annotation) {
        if (annotation == null) {
            return;
        }
        for (String origin : annotation.origins()) {
            config.addAllowedOrigin(resolveCorsAnnotationValue(origin));
        }
        for (RequestMethod method : annotation.methods()) {
            config.addAllowedMethod(method.name());
        }
        for (String header : annotation.allowedHeaders()) {
            config.addAllowedHeader(resolveCorsAnnotationValue(header));
        }
        for (String header : annotation.exposedHeaders()) {
            config.addExposedHeader(resolveCorsAnnotationValue(header));
        }

String allowCredentials = resolveCorsAnnotationValue(annotation.allowCredentials());
        if ("true".equalsIgnoreCase(allowCredentials)) {
            config.setAllowCredentials(true);
        }
        else if ("false".equalsIgnoreCase(allowCredentials)) {
            config.setAllowCredentials(false);
        }
        else if (!allowCredentials.isEmpty()) {
            throw new IllegalStateException("@CrossOrigin's allowCredentials value must be \"true\", \"false\", " +
                    "or an empty string (\"\"): current value is [" + allowCredentials + "]");
        }

if (annotation.maxAge() >= 0 && config.getMaxAge() == null) {
            config.setMaxAge(annotation.maxAge());
        }
    }

Spring MVC 跨域处理-立哥技术相关推荐

  1. Spring Boot 系统日志代码解析-立哥技术

    // 男儿何不把吴钩,收取关山五十州 public static LoggingSystem get(ClassLoader classLoader) {     // 获取系统属性     Stri ...

  2. 实战系列-Spring Boot跨域解决方案

    导语   在实际工作开发中经常会遇到跨域请求,这个时候就需要前后端来共同协调来解决问题,那么在Spring Boot中怎么解决跨域请求问题呢?下面就来看看 什么是跨域   为了保证浏览器的安全,不同源 ...

  3. kuayu react_React+Spring实现跨域问题的完美解决方法

    最近小编在学习react,在学习过程中遇到React+Spring实现跨域问题,下面小编记录了整个问题过程,给大家做个参考. react 跨域访问后台,默认是有跨域问题,并且火弧和谷歌浏览器,对跨域问 ...

  4. react+spring 记录跨域问题的解决方法

    react+spring 记录跨域问题的解决方法 参考文章: (1)react+spring 记录跨域问题的解决方法 (2)https://www.cnblogs.com/cq-jiang/p/954 ...

  5. Spring Security跨域问题解决

    前文介绍了:Spring 处理跨域问题的三种方案 现在来看看 Spring Security 的跨域问题解决方案,共有三种方案.(摘自<深入浅出Spring Security>) 在实际项 ...

  6. webmvcconfigurer配置跨域_为什么加了 Spring Security 会导致 Spring Boot 跨域失效呢?...

    点击上方 IT牧场 ,选择 置顶或者星标 技术干货每日送达 作者:欧阳我去 链接:https://segmentfault.com/a/1190000019485883 作为一个后端开发,我们经常遇到 ...

  7. Spring处理跨域请求

    [nio-8080-exec-8] o.s.web.cors.DefaultCorsProcessor        : Skip CORS processing: request is from s ...

  8. 前端vue发送给后端MVC跨域问题

    在Vue脚手架项目中使用axios 首先,需要安装axios,则在终端窗口中,在当前项目文件夹下,执行安装命令: npm i axios -S 然后,需要在main.js中添加配置: import a ...

  9. spring boot跨域问题

    跨域是指不同域名之间相互访问.跨域,指的是浏览器不能执行其他网站的脚本.它是浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制.也就是如果在A网站中,我们希望使用Ajax来获得B网站 ...

最新文章

  1. Runtime编译环境搭建
  2. 阿里达摩院AI抗疫最新战报:已诊断3万多疑似病例CT影像,准确率96%
  3. 计算机网络和传统电话网络的最大区别是,传统电话和网络电话有什么区别
  4. AIDL Service,跨进程调用Services
  5. spring.shardingsphere.rules.sharding.sharding-algorithms.database_inline.props‘ is not valid
  6. SpringBoot Redis缓存 @Cacheable、@CacheEvict、@CachePut
  7. matlab的knn均值滤波,中值滤波与均值滤波介绍.ppt
  8. Docker架构、常用命令和示例
  9. web安全day37:Linux脚本判断和循环,编写脚本实现内网主机存活批量检测
  10. 微博html5版登录网址,微博网页版登录入口
  11. 申请并部署阿里云SSL免费证书详细流程
  12. 【论文】AlexNet 一
  13. 计算机网络中 89 个常见的概念
  14. 一、PostgreSQL软件安装
  15. python transformat_Python transforms.Bbox方法代码示例
  16. 1#includestdio.h #includestring.h int deng(char a[],ch、用函数实现登陆功能(三次机会),然后在主函数中根据调用后的结果判断 登陆成功与否。
  17. ASP.NET MVC3实践
  18. Computational Imaging 计算成像(二)
  19. 【SEO教程网】网站内部链接优化的四大技巧
  20. 终于来了,iOS14.5.1越狱简易版,你成功了吗?

热门文章

  1. fedora安装fcitx输入法
  2. vncapp下载,vncapp下载怎么下载?下载教程
  3. w ndows7太卡了,完美解决windows7卡在正在启动windows 一直卡在正在启动window
  4. Tensorflow(一) —— 数据类型
  5. 你本是无意指尖穿堂风,我偏偏心有惊鸿付余生。
  6. 最好的芳华遇到你,余生都是你
  7. 西数硬盘linux,SMR硬盘可靠性不再是问题 西数神油ZoneFS系统纳入Linux中
  8. 智能手机与pc计算机的区别,手机cpu与电脑cpu有啥区别?
  9. 致可爱的仙女程序“媛“们
  10. jsp中重定向和转发的区别