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

相关推荐
特立独行的猫A7 小时前
用仓颉语言 cj-tauri 框架,五分钟给娃做了个鸿蒙形近字游戏
java·后端·python
码事漫谈10 小时前
我花了一周时间,看AI公司怎么"管"AI,结果越看越后背发凉
后端
爱学习的程序媛13 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
GISer_Jing13 小时前
Agent核心内容
后端·ai·langchain
budingxiaomoli14 小时前
Spring统一功能处理
java·后端·spring
某鹏15 小时前
网关选型:Go、Java、Graal 谁都不能完胜
后端
用户02478365309715 小时前
从屎山到防线:14 行状态迁移表,给任务系统装上防瞎跳闸门
后端
CQU_JIAKE15 小时前
11.13[体系结构】指标,五级流水线,八级流水线,虚实地址思考
后端
Flynn Liang15 小时前
可观测性与成本治理:一次对话的 17 个观测点
java·langchain·可观测性·micrometer·langchain4j·token 成本·llm 监控
金銀銅鐵16 小时前
带您看懂字节码指令(三):同一行加法,为什么有四种指令
java·jvm