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 小时前
SpringMVC 入门到实战 文件上传 75-77
java·后端·spring·maven·intellij-idea
GIS数据转换器1 小时前
城市排水生命线安全运行监测平台深度解析
java·运维·人工智能·python·安全·数据挖掘·无人机
华如锦2 小时前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai
睡不醒男孩0308232 小时前
CLup 6.x 版本中针对StarRocks 存算一体集群的完整操作手册
java·服务器·网络·clup
程序员黑豆3 小时前
Java中怎么实现字符串拼接呢【AI全栈开发】
java
fox_lht3 小时前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
大鸡腿同学3 小时前
用 AI 肝了一个星期的智能客服助手,看看怎么个事
后端
IT_陈寒3 小时前
Python的os.path.join居然能这么坑?
前端·人工智能·后端
java1234_小锋3 小时前
LangChain4j 开发Java Agent智能体- 多模态支持
java·开发语言·langchain4j