解析 RESTful API 中的 URI 参数

Parsing URI parameters in a RESTful API

我应该如何在 REST 中解析 URI 参数 API。例如:

http://api.example.com/item/ [{{ItemID}} [/{{Property}}]]

以下请求均应有效:

http://api.example.com/item
http://api.example.com/item/
http://api.example.com/item/1
http://api.example.com/item/1/
http://api.example.com/item/1/description
http://api.example.com/item/1/description/

我需要能够获取 ItemID 和 属性 值(如果存在)。

我尝试使用 Apache Commons StringUtils 和 substringBefore/substringAfter,但事情很快就变得混乱了。是否有用于此类任务的库,或者我忽略的其他方式?

如果您使用的是 JAX-RS,您可以这样做

@GET
@Path("/{param1}/{param2}")
@Produces("text/plain")

public String get(@PathParam("param1") int param1, @PathParam("param2") int param2) {

    logger.debug("\n param1 = " + param1 + " .. param2 = " + param2);
}

我非常感谢@Jagdeep 的回答,但由于我没有使用 JAX-RS,所以无法使用它。在做了一些研究之后,很明显没有任何库可以做到这一点,所以我决定创建自己的库。它非常粗糙,目前还没有文档。不过,我会尽快更新。欢迎您向我提交拉取请求,并进行改进。

https://github.com/ArjMart/UrlParser

用法:

UrlParser parser = new Parser();
parser.setTemplate("/item/{INT:itemID}/{STRING:itemAttribute}");
UrlParametersMap upm = parser.parse(request.getURI());
boolean attributeExists = upm.parameterExists("itemAttribute");
String attribute = null;
if(attributeExists){
  attribute = upm.getString("itemAttribute");
}

免责声明: 我(显然)隶属于 UrlParser,因为我是它的唯一创建者和贡献者。