RESTful servlet URL - web.xml 中的 servlet 映射 [英] RESTful servlet URLs - servlet-mapping in web.xml
问题描述
我觉得这是一个常见问题,但我研究的任何内容都没有奏效...
I feel like this is a common problem but nothing I've researched has worked yet...
在我的 web.xml 中,我有一个所有 REST 调用的映射 -
In my web.xml I have a mapping for all REST calls -
<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
错误,说明 客户端发送的请求在语法上不正确 ()
.我不确定它是否已经进入 Spring servlet 以进行路由...
I get a 400 Bad Request
error saying The request sent by the client was syntactically incorrect ()
. I'm not sure it even made it to the Spring servlet to get routed...
如何通配以 /rest
开头的任何内容,以便对其进行适当处理?
How can I wildcard anything that starts with /rest
so that it can be handled appropriately?
换句话说,我希望以下所有内容都是有效的 -
In other words, I'd like for all of the following to be valid -
GET /rest/people
GET /rest/people/1
GET /rest/people/1/phones
GET /rest/people/1/phones/23
编辑 - 按照要求的控制器代码
Edit - Controller code as requested
@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 是否有 /
似乎并不重要.
@matsev It didn't seem to matter if I had the /
there or not.
当我为公共视图转置变量名称时,我更改了一些内容以使其正常工作.
While I was transposing the variable names for public view I changed a couple things to make it work.
原创
@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));
}
变量名不匹配让我...我把它留在这里作为对所有人的警告...匹配你的变量名!
推荐答案
尝试在 {id}
之前添加一个 /
:
Try add a /
before the {id}
:
@RequestMapping(value="/{id}", method=RequestMethod.GET)
没有它,id 将直接附加到人们的 url,例如 /rest/people1
而不是 /rest/people/1
.
Without it, the id will be appended directly to the people url, e.g /rest/people1
as opposed to /rest/people/1
.
这篇关于RESTful servlet URL - web.xml 中的 servlet 映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!