如何使用@WebServlet接受参数(以RESTFul方式)?

pis*_*hio 1 java rest servlets servlet-3.0

假设我想接受以下网址:

http://myserver/myapplication/posts
http://myserver/myapplication/posts/<id>
http://myserver/myapplication/posts/<id>/delete
Run Code Online (Sandbox Code Playgroud)

我怎样才能使用servlet装饰器@WebServlet呢?我正在调查value,urlPatterns但我不知道怎么做.例如,

@WebServlet(urlPatterns={"/posts", "/posts/*"})
[..]
String param = request.getPathInfo();
Run Code Online (Sandbox Code Playgroud)

给我一些结果,但如何使用它?此外,request.getPathInfo()似乎返回通配符的值,但如果我想要更多的参数,如果http://http://myserver/myapplication/posts/<id>/delete/<force>

Ser*_*sta 7

在servlet规范中,您没有路径变量的概念.一些MVC框架确实支持它们,例如Struts或Spring MVC.

对于servlet的观点,URL是:

scheme://host.domain/context_path/servlet_path/path_info?parameters
Run Code Online (Sandbox Code Playgroud)

任何部分(从上下文路径开始可能为null)

servlet 3.0的规范说明:

  • Context Path:与此Servlet所属的ServletContext相关联的路径前缀.如果此上下文是以Web服务器的URL名称空间为基础的"默认"上下文,则此路径将为空字符串.否则,如果上下文未以服务器名称空间的根目录为根,则路径以/字符开头,但不以/字符结尾.
  • Servlet路径:与激活此请求的映射直接对应的路径部分.此路径以"/"字符开头,但请求与"/*"或""模式匹配的情况除外,在这种情况下,它是一个空字符串.
  • PathInfo:请求路径中不属于Context Path或Servlet Path的部分.如果没有额外路径,则为null,或者是带有前导'/'的字符串.

HttpServletRequest接口中存在以下方法来访问此信息:

  • getContextPath
  • getServletPath
  • getPathInfo

值得注意的是,除了URL编码请求URI和路径部分之间的差异之外,以下等式始终为真:

requestURI = contextPath + servletPath + pathInfo
Run Code Online (Sandbox Code Playgroud)

这意味着你只需要使用@WebServlet(urlPatterns={"/posts"}),然后手工解码pathInfo部分来提取命令和参数