-->

REST风格的servlet的URL - 在web.xml中的servlet映射(RESTful

2019-09-16 07:44发布

我觉得这是一个常见的问题,但没有我研究还没有工作...

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

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

这种运作良好,如果URL -

GET /rest/people

失败如果是

GET /rest/people/1

我得到一个400 Bad Request错误消息, The request sent by the client was syntactically incorrect () 我不知道它甚至去到春节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));
}

变量名称不匹配确实我......我离开这个位置,以警示所有...匹配您的变量名!

Answer 1:

尝试添加/的前{id}

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

没有它,ID将直接附加到人URL,例如/rest/people1而不是/rest/people/1



文章来源: RESTful servlet URLs - servlet-mapping in web.xml