简体   繁体   English

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

[英]How to define priorities for request mappings in Spring MVC?

Using SpringMVC, I have a method that catch all REST requests: 使用SpringMVC,我有一个捕获所有REST请求的方法:

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

Now I would like to catch just a few requests with the following endpoint: 现在,我想用以下端点捕获一些请求:

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

Right now, when I call: 现在,当我打电话给:

/test /测试

the second method is never called. 从不调用第二种方法。

What can I do to have my 2nd method always called in place of the first one? 要使我的第二个方法始终代替第一个方法,该怎么办?

First of all as Asura points out, do not implement a 'catchAll' method. 首先,正如Asura所指出的,不要实现'catchAll'方法。 Having said that, Spring MVC allows you to use regular expressions in URL(s). 话虽如此,Spring MVC允许您在URL中使用正则表达式。

Read the documentation for using regular expressions in Spring URL(s) here . 此处阅读在Spring URL中使用正则表达式的文档。

In your case, use a negative lookahead in your first URL to remove the ones that start with /test . 在您的情况下,请在第一个URL中使用否定前瞻,以删除以/test开头的内容。 That way your /** controller will catch all requests except the ones that start with /test and you can use your other controller to catch those. 这样,您的/**控制器将捕获除以/test开头的请求之外的所有请求,您可以使用其他控制器来捕获这些请求。

Use negative lookahead in your first URL: 在第一个网址中使用否定的超前查询:

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

} }

Now, this should catch /test requests: 现在,这应该捕获/test请求:

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM