我正在玩弄 Jersey 2.21
我想知道是否可以有一个“可选”参数,它可以或不可以出现在对服务器的请求中.
我想成功访问这两个方法:
http://localhost:8080/my_domain/rest/api/myMethod/1
http://localhost:8080/my_domain/rest/api/myMethod
如您所见,我正在尝试使整数 (id
) 参数成为可选参数。
我声明了 myMethod
如下:
@GET
@Path("myMethod/{id}")
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public String myMethod(@PathParam("id") Integer id, @Context HttpHeaders hh)
这个有效:
http://localhost:8080/my_domain/rest/api/myMethod/1
这也行:
http://localhost:8080/my_domain/rest/api/myMethod/
但是这行不通,我不明白为什么。它抛出一个 404 Not Found
错误:
http://localhost:8080/my_domain/rest/api/myMethod
你能指出正确的方向来解决这个问题吗?我不喜欢在我的所有 REST 方法调用中强制使用斜杠,并希望尽可能禁止使用它。
最佳答案
有一种方式可以更简单地做到这一点:
@GET
@Path("myMethod/{id}")
public String myMethod(@PathParam("id") Integer id) {
}
@GET
@Path("myMethod")
public String myMethod() {
return myMethod(null);
}
不需要棘手的正则表达式。
关于java - 使用 Jersey 2.21 的 REST API 请求中的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32765804/