如何在REST API中解析URI参数。例如:
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和Property值(如果存在)。
我尝试使用Apache Commons StringUtils和substringBefore / substringAfter,但事情很快就让人困惑。是否存在用于此类任务的库,或者我忽略的另一种方式?
答案 0 :(得分:1)
如果您使用的是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);
}
答案 1 :(得分:0)
我非常感谢@ 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有关联,因为我是其唯一的创建者和贡献者。