子控制器中缺少Spring-API设计父母标识

时间:2018-09-09 10:37:54

标签: java spring spring-boot

我正在使用Spring Boot设计API。

我正在Spring-boot中实现以下API设计。

  1. localhost:8989 //父母。
  2. localhost:8989 //父母/父母
  3. localhost:8989 ///父母/父母/孩子

下面的控制器,我已经实现了。

@RestController
@RequestMapping(
 path="/parent",
 consumes=MediaType.APPLICATION_JSON_VALUE,
 produces=MediaType.APPLICATION_JSON_VALUE)
 public class ParentController {
         @RequestMapping(method=RequestMethod.GET)
         public @ResponseBody ResponseObject getAllParent() {
            //code to return all parent
         }      
         @RequestMapping(method=RequestMethod.GET, path="{id}")
         public @ResponseBody ResponseObject getParent(@PathVariable("id") 
                                               Integer parentid) {
              //code to return specific parent
         }
         @RequestMapping(method=RequestMethod.GET, path="{id}/child")
         public @ResponseBody ResponseObject getParentChild 
                                    (@PathVariable("id")Integer parentid) {
              //code to return specific parent
         }
  }

我在此请求以下请求。

  1. localhost:8989 // parent->运行正常
  2. localhost:8989 // parent / parentid->工作正常
  3. localhost:8989 // parent / parentid / child->无法正常工作。遇到错误。

    {     “ timestamp”:“ 2018-09-09T09:44:05.922 + 0000”,     “状态”:500,     “错误”:“内部服务器错误”,     “ message”:“缺少Integer类型的方法参数的URI模板变量'parentid'”,     “路径”:“ / parent / 1536485852 / child /” }

对此有任何帮助吗?

1 个答案:

答案 0 :(得分:2)

请更改此方法;

 @RequestMapping(method=RequestMethod.GET, value = "{id}/child")
         public @ResponseBody ResponseObject getParentChild 
                                    (@PathVariable("id")Integer parentid) {
              //code to return specific parent
         }

这里path="{id}/child"是错误的。在此添加斜杠。所以就像这样;

value="/{id}/child"

如果您不在此处添加斜杠,它将连接两个路径。因此,"parent"之一是"{id}/child"。因此,未知。将两者连接在一起,结果将类似于"parentid/child"。在您的例外情况下,找不到parentid。您的路径网址不符合您的要求。不久在这里添加斜杠。