如何使用@WebServlet 接受参数(以 RESTFul 方式)? [英] How to use @WebServlet to accept arguments (in a RESTFul way)?

查看:70
本文介绍了如何使用@WebServlet 接受参数(以 RESTFul 方式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想接受以下网址:

suppose that I want to accept the following urls:

http://myserver/myapplication/posts
http://myserver/myapplication/posts/<id>
http://myserver/myapplication/posts/<id>/delete

我如何使用 servlet 装饰器 @WebServlet 来做到这一点?我正在调查 valueurlPatterns 但我不知道如何去做.例如,

how can I use the servlet decorator @WebServlet to do so? I'm investigating value and urlPatterns but I don't get how to do so. For example,

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

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

gives me some result, but how to use it? Also, request.getPathInfo() seems to return the value of the wildcard, but what if I want more parameters like in http://http://myserver/myapplication/posts/<id>/delete/<force>?

推荐答案

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

In servlet specification, you have no notion of path variables. Some MVC frameworks do support them, for example Struts or Spring MVC.

对于 servlet 的观点,URL 是:

For a servlet point of view, an URL is :

scheme://host.domain/context_path/servlet_path/path_info?parameters

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

where any of the parts (starting from context path may be null)

servlet 3.0 状态规范:

Spec for servlet 3.0 states :

  • Context Path:与这个 ServletContext 关联的路径前缀servlet 是其中的一部分.如果此上下文是根植于Web 服务器的 URL 名称空间,此路径将为空字符串.否则,如果上下文不是以服务器命名空间的根为根,路径以/字符但不以/字符结尾.
  • Servlet Path:直接对应的映射的路径部分激活了这个请求.此路径以/"字符开头,但情况除外其中请求与/*"或"模式匹配,在这种情况下,它是一个空字符串.
  • PathInfo:请求路径中不属于 Context Path 或小服务程序路径.如果没有额外的路径,则它要么是 null,要么是带有前导的字符串‘/’.

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

The following methods exist in the HttpServletRequest interface to access this information:

  • getContextPath
  • getServletPath
  • 获取路径信息

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

It is important to note that, except for URL encoding differences between the request URI and the path parts, the following equation is always true:

requestURI = contextPath + servletPath + pathInfo

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

That means that you just have to use @WebServlet(urlPatterns={"/posts"}), and then decode by hands the pathInfo part to extract commands and parameters

这篇关于如何使用@WebServlet 接受参数(以 RESTFul 方式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆