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~~

相关推荐
Justin3go13 小时前
HUNT0 上线了——尽早发布,尽早发现
前端·后端·程序员
Tony Bai13 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
十月南城13 小时前
Spring Cloud生态地图——注册、配置、网关、负载均衡与可观测的组合拳
spring·spring cloud·负载均衡
没有bug.的程序员13 小时前
服务安全:内部服务如何防止“裸奔”?
java·网络安全·云原生安全·服务安全·零信任架构·微服务安全·内部鉴权
一线大码14 小时前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端
weixin_4407305014 小时前
java数组整理笔记
java·开发语言·笔记
weixin_4250230014 小时前
Spring Boot 配置文件优先级详解
spring boot·后端·python
weixin_4250230014 小时前
Spring Boot 实用核心技巧汇总:日期格式化、线程管控、MCP服务、AOP进阶等
java·spring boot·后端
一线大码14 小时前
Java 8-25 各个版本新特性总结
java·后端
2501_9061505614 小时前
私有部署问卷系统操作实战记录-DWSurvey
java·运维·服务器·spring·开源