java - 如何在 Spring MVC 中定义请求映射的优先级?

标签 java spring rest spring-mvc

使用 SpringMVC,我有一个捕获所有 REST 请求的方法:

@RequestMapping(value = "/**")
public Object catchAll(@RequestBody(required = false) Object body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) {
    // ...
}

现在我只想使用以下端点捕获一些请求:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public Object post(@RequestBody Object body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) {
    // ...
}

现在,当我打电话时:

/test

第二个方法永远不会被调用。

如何才能始终调用第二个方法来代替第一个方法?

最佳答案

首先为Asura指出,不要实现“catchAll”方法。话虽如此,Spring MVC 允许您在 URL 中使用正则表达式。

阅读有关在 Spring URL 中使用正则表达式的文档 here

就您的情况而言,请在第一个 URL 中使用否定前瞻来删除以 /test 开头的 URL。这样,您的 /** Controller 将捕获除以 /test 开头的请求之外的所有请求,并且您可以使用其他 Controller 来捕获这些请求。

在第一个 URL 中使用否定前瞻:

@RequestMapping(value = "/^(?!test)")
public Object catchAll(@RequestBody(required = false) Object body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) {
// ...

}

现在,这应该捕获 /test 请求:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public Object post(@RequestBody Object body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) {
// ...

}

关于java - 如何在 Spring MVC 中定义请求映射的优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418577/

相关文章:

rest - XPOST 和 XPUT 的区别

java - 是否可以在没有 web.xml 文件的情况下在 jetty 上运行 servlet?

JDK8 改变了 Javadoc 布局

java - 如何仅使用 Google Cloud Endpoints 配置模型映射器一次?

java - 添加到数据库 rest webservice

java - 如何创建接收 Gson().fromJson() 的对象

java - 如何解决 Oracle 中的 setString max 32766 字符问题?

java - 集成 OpenAPI 3.0 架构以进行 Spring Boot json 响应测试

java - Spring : Spring scheduler with fixed-rate param work incorrectly

java - 从 SQLServer 到 Java 的通知