spring-webmvc根据请求路径找到对应的 HandlerMethod

代码中有的时候想通过请求地址获得对应的controller处理方法(此时HttpServletRequest对象还没有生成),可以使用以下方法(以spring-webmvc6.1.2版本为示例)

复制代码
    @Resource
    private RequestMappingHandlerMapping handlerMapping;

    /**
     * 根据请求地址找到对应的 HandlerMethod
     *
     * @param requestURI 请求地址
     * @return HandlerMethod
     */
    private HandlerMethod getHandlerMethodByRequestURI(String requestURI) throws Exception {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();

        Object mappingRegistry = ObjectUtil.getValue(handlerMapping, "mappingRegistry");
        if (Objects.equals(mappingRegistry.getClass().getName(), "org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry")) {
            Field pathLookup = mappingRegistry.getClass().getDeclaredField("pathLookup");
            pathLookup.setAccessible(true);
            Object o = pathLookup.get(mappingRegistry);
            System.out.println(o);
            if (o instanceof Map map) {
                Object o1 = map.get(requestURI);
                if (o1 instanceof List list && CollectionUtil.isNotEmpty(list)) {
                    HandlerMethod handlerMethod = handlerMethods.get(list.get(0));
                    
                    System.out.println(handlerMethod);
                    return handlerMethod; 
                }
            }
        }
        return null;
    }

拿到HandlerMethod 进而可以获得对应的反射Method,进而获取到方法上的注解,可以做很多事情了

over~~

相关推荐
无声旅者1 小时前
深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
java·ide·ai·intellij-idea·ai编程·continue·openapi
Ryan-Joee1 小时前
Spring Boot三层架构设计模式
java·spring boot
Hygge-star1 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
dkmilk2 小时前
Tomcat发布websocket
java·websocket·tomcat
工一木子2 小时前
【Java项目脚手架系列】第七篇:Spring Boot + Redis项目脚手架
java·spring boot·redis
哞哞不熬夜2 小时前
JavaEE--初识网络
java·网络·java-ee
noravinsc2 小时前
redis是内存级缓存吗
后端·python·django
等等5432 小时前
Java EE初阶——wait 和 notify
java·开发语言
沛沛老爹3 小时前
软件架构风格系列(2):面向对象架构
spring·软件架构风格·面向对象架构·架构入门
API小爬虫3 小时前
淘宝按图搜索商品(拍立淘)Java 爬虫实战指南
java·爬虫·图搜索算法