我正在尝试使应用程序的 REST API 更加 RESTful,但感觉我没有按照预期的方式使用 Spring RequestMappings。
我有一个用于读取的 GET 端点:
@RequestMapping(value = "thing/{thingName}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getThing(
@PathVariable(value = "thingName", required = false)
String thingName,
@RequestParam(value = "findByComponent", required = false)
String findByComponentQuery,
@AuthenticationPrincipal User user) {
...
为了更加轻松,我希望此端点同时执行以下两项操作:
- GET/thing/{thingName} 返回具有该名称的单个事物
- 带有查询参数的 GET/thing 或/thing/返回事物列表
因此,在我的 Controller 中,我可以测试 {thingName}
是否为空或零长度,如果是,请检查查询参数中是否有已知的查询名称。
但是使用 http://localhost:8080/thing/?findByComponent=component123
调用它会从 Spring 返回 404 并记录以下日志:
12:45:18.485 PageNotFound : No mapping found for HTTP request with URI [/thing/] in DispatcherServlet with name 'dispatcher' : WARN : XNIO-1 task-3 : org.springframework.web.servlet.DispatcherServlet
最佳答案
Spring 不允许路径变量 ( {thingName}
) 映射到空 String
。实际上,这意味着 URL /thing/?findByComponent=component123
不映射到thing/{thingName}
与空 {thingName}
,而是,它期望 thing
有一些映射。由于没有端点映射到路径 thing
(没有路径变量),a 404
返回错误。
要解决此问题,您可以将此单个端点分解为两个单独的端点:
@RequestMapping(value = "thing/{thingName}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getThing(
@PathVariable(value = "thingName") String thingName,
@AuthenticationPrincipal User user) {
// ...
}
@RequestMapping(value = "thing",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getThings(,
@RequestParam(value = "findByComponent", required = false) String findByComponentQuery,
@AuthenticationPrincipal User user) {
// ...
}
有关详细信息,请参阅 With Spring 3.0, can I make an optional path variable? .
required=false
标志允许两种类型的请求:
-
/thing
-
/thing/<some_value>
严格来说,在 URL 末尾包含尾部斜杠(即 /thing/
)意味着已决定包含路径变量的值,但没有提供任何值。在 REST API 的上下文中,/thing
和/thing/
是两个不同的端点,其中后者意味着尾部斜杠后面的值是预期的。
无需创建三个单独的请求映射(上述每种情况一个)的解决方法是设置 @RequestMapping
将 Controller 的值添加到基本路径,然后有 ""
和"/{thingName}
两个端点的请求映射:
@RestController
@RequestMapping("thing")
public class ThingController {
@RequestMapping(value = "/{thingName}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getThing(
@PathVariable(value = "thingName") String thingName) {
return "foo";
}
@RequestMapping(value = "",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getThings(
@RequestParam(value = "findByComponent", required = false) String findByComponentQuery) {
return "bar";
}
}
在这种情况下,将发生以下映射:
-
/thing
:getThings
-
/thing/
:getThings
-
/thing/foo
:getThing
此解决方法的示例(包括测试用例)可以是 found here .
关于java - Spring Controller RequestMapping PathVariable 中 URL 的零长度部分破坏了解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54075183/