使用 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/