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

相关推荐
是小蟹呀^39 分钟前
Spring Security + JWT 面试题整理
java·jwt·springsecurity
spencer_tseng3 小时前
Redis + Nacos.bat
java·windows·dos
霸道流氓气质3 小时前
SpringBoot中通用工具类库(Utils)封装与使用实践
spring boot·后端·python
troyzhxu3 小时前
列表查询的 GraphQL —— 一行代码终结你的 if-else 地狱!
java·springboot·graphql
孫治AllenSun4 小时前
【DataX】生产环境搭建DataX集群案例
java·开发语言·jvm
好好沉淀5 小时前
@NotBlank(message = “{xxx}“) 注解中花括号的含义
java
fīɡЙtīиɡ ℡5 小时前
内存泄漏产生的原因
java·spring·servlet
hkj88085 小时前
Ubuntu 切换java版本
java·linux·ubuntu