Spring:检查给定端点是否存在

Spring:检查给定端点是否存在

问题描述:

就像标题一样.我想知道,是否有简单的方法来检查给定的路径是否可以转换到任何控制器中存在的 (API) 端点.

Just like in title. I wonder, if there is simple way to check if given path can traslate to (API) endpoint that exists in any controller.

我有一个优先级最高的自定义过滤器,如果给定的请求不会产生任何结果(端点不存在),我想返回 404 状态代码.

I have a custom filter with highest precedence and I want to return 404 status code if given request won't yield any results (endpoint doesn't exist).

查看RequestMappingHandlerMapping 类,特别是它的 getHandlerMethods 方法.

来自文档:

public MapgetHandlerMethods()

返回包含所有映射和 HandlerMethod 的(只读)映射.

Return a (read-only) map with all mappings and HandlerMethod's.

对于RequestMappingHandlerMappingTRequestMappingInfo.

来自 RequestMappingInfo 文档:

From RequestMappingInfo docs:

封装了以下请求映射条件:

Encapsulates the following request mapping conditions:

  1. 模式请求条件
  2. RequestMethodsRequestCondition
  3. 参数请求条件
  4. HeadersRequestCondition
  5. ConsumesRequestCondition
  6. ProducesRequestCondition
  7. RequestCondition(可选,自定义请求条件)

来自HandlerMethod 文档:

封装有关由方法和 bean 组成的处理程序方法的信息.提供对方法参数、方法返回值、方法注解的便捷访问.

Encapsulates information about a handler method consisting of a method and a bean. Provides convenient access to method parameters, method return value, method annotations.

如果您想从过滤器 bean 执行此操作,您可以将 RequestMappingHandlerMapping bean 自动装配到它:


If you want to do this from a filter bean, you could just autowire RequestMappingHandlerMapping bean to it:

@Component
public class MyFilterBean extends OncePerRequestFilter {

    @Autowired
    RequestMappingHandlerMapping mappings;

}