简体   繁体   中英

How to define priorities for request mappings in Spring MVC?

Using SpringMVC, I have a method that catch all REST requests:

@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. Having said that, Spring MVC allows you to use regular expressions in URL(s).

Read the documentation for using regular expressions in Spring URL(s) here .

In your case, use a negative lookahead in your first URL to remove the ones that start with /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.

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:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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