2015-05-23 87 views
1

使用用SpringMVC,我有一个捕获所有REST请求的方法:如何在Spring MVC中定义请求映射的优先级?

@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) { 
    // ... 
} 

现在,当我打电话:

/测试

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

我能做些什么来让我的第二个方法总是被调用来代替第一个方法?

+1

你不应该有抓到什么所有请求都像方法1. – Asura

回答

0

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

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

对于您的情况,请在您的第一个网址中使用负向视图来移除以/test开头的视图。这样,您的/**控制器将会捕获除了以/test开头的所有请求,并且您可以使用其他控制器来捕获这些请求。

使用您的第一个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) { 
// ... 

}

+0

你能否详细说明为什么ac应该避免所有的问题? –