就像标题一样。我想知道,如果有简单的方法来检查给定的路径是否可以转换到任何控制器中存在的(API)端点。
我有一个优先级最高的自定义过滤器,如果给定的请求不会产生任何结果(端点不存在),我想返回404状态代码。
答案 0 :(得分:2)
要执行此操作,您需要创建一个将RequestMappingHandlerMapping作为属性的过滤器。像这样:
public class AllHandlersList extends OncePerRequestFilter {
RequestMappingHandlerMapping requestMappingHandlerMapping;
public AllHandlersList(RequestMappingHandlerMapping requestMappingHandlerMapping) {
this.requestMappingHandlerMapping = requestMappingHandlerMapping;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
//Add you own logic here ot handle the request your way.
System.out.println(requestMappingHandlerMapping.getHandler(request).getHandler());
} catch (Exception e) {
e.printStackTrace();
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
然后你需要注册它。我看到你使用spring boot,所以你可以将它添加到你的java配置中:
@Bean
@Autowired
public FilterRegistrationBean listHandlers(RequestMappingHandlerMapping requestMappingHandlerMapping) {
FilterRegistrationBean register = new FilterRegistrationBean();
register.setFilter(new AllHandlersList(requestMappingHandlerMapping));
register.setName("handlerListFilter");
register.setUrlPatterns(Arrays.asList(new String[]{"/"}));
register.setOrder(Ordered.HIGHEST_PRECEDENCE);
return register;
}
答案 1 :(得分:1)
查看RequestMappingHandlerMapping
课程,尤其是getHandlerMethods
方法。
来自文档:
public Map<T,HandlerMethod> getHandlerMethods()
返回包含所有映射和HandlerMethod的(只读)映射。
对于RequestMappingHandlerMapping
,T
为RequestMappingInfo
。
封装以下请求映射条件:
- PatternsRequestCondition
- RequestMethodsRequestCondition
- ParamsRequestCondition
- HeadersRequestCondition
- ConsumesRequestCondition
- ProducesRequestCondition
- RequestCondition(可选,自定义请求条件)
醇>
封装有关由方法和bean组成的处理程序方法的信息。提供对方法参数,方法返回值,方法注释的方便访问。
如果您想从过滤器bean中执行此操作,您可以将RequestMappingHandlerMapping
bean自动装配到它:
@Component
public class MyFilterBean extends OncePerRequestFilter {
@Autowired
RequestMappingHandlerMapping mappings;
}