小编典典

RESTful servlet URL-web.xml中的servlet映射

spring-mvc

我觉得这是一个普遍的问题,但我研究过的任何方法都没有起作用……

在我的web.xml中,我有一个所有REST调用的映射-

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

如果网址为-

GET /rest/people

但是 失败

GET /rest/people/1

我得到一个400 Bad Request错误的说法The request sent by the client was syntactically incorrect ()。我不确定它甚至到达Spring servlet进行路由…

我如何通配以 任何 开头的内容,/rest以便可以正确处理?

换句话说,我希望以下所有内容都有效-

GET /rest/people
GET /rest/people/1
GET /rest/people/1/phones
GET /rest/people/1/phones/23

编辑 -要求的控制器代码

@Controller
@RequestMapping("/people")
public class PeopleController {

    @RequestMapping(method=RequestMethod.GET)
    public @ResponseBody String getPeople() {
        return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPeople());
    }

    @RequestMapping(value="{id}", method=RequestMethod.GET)
    public @ResponseBody String getPerson(@PathVariable String id) {
        return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPerson(id));
    }
}

回答

@matsev是否在那似乎无关紧要/

当我将变量名转换为公开视图时,我做了一些更改以使其起作用。

原版的

@RequestMapping(value="{id}", method=RequestMethod.GET)
public @ResponseBody String getPerson(@PathVariable String userId) {
    return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPerson(userId));
}

我发布了什么

@RequestMapping(value="{id}", method=RequestMethod.GET)
public @ResponseBody String getPerson(@PathVariable String id) {
    return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPerson(id));
}

变量名不匹配是我造成的……我在此警告所有…匹配您的变量名!


阅读 341

收藏
2020-06-01

共1个答案

小编典典

尝试在/之前添加{id}

@RequestMapping(value="/{id}", method=RequestMethod.GET)

如果没有它,则id将直接附加到人员网址(例如/rest/people1与相对)/rest/people/1

2020-06-01