Java 如何使用可选参数创建 REST API?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35715191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create REST API with optional parameters?
提问by mbgsuirp
I need to implement an API with these path params.
我需要使用这些路径参数来实现一个 API。
@Path("/job/{param1}/{optional1}/{optional2}/{param2}")
Can the second and third params by optional? So the client need not pass these, but have to pass the first and last.
可以选择第二个和第三个参数吗?所以客户端不需要通过这些,但必须通过第一个和最后一个。
If this is not possible, then is it recommended to rearrange the params in this way?
如果这是不可能的,那么是否建议以这种方式重新排列参数?
@Path("/job/{param1}/{param2}/{optional1}/{optional2}")
How to provide the optional params?
如何提供可选参数?
采纳答案by Emdadul Sawon
You can match the entire path ending in the REST request
您可以匹配以 REST 请求结尾的整个路径
@Path("/location/{locationId}{path:.*}")
public Response getLocation(
@PathParam("locationId") int locationId,
@PathParam("path") String path) {
//your code
}
Now the path variable contain entire path after location/{locationId}
现在路径变量包含整个路径 location/{locationId}
You can also use regular expression to make path optional.
您还可以使用正则表达式使路径可选。
@Path("/user/{id}{format:(/format/[^/]+?)?}{encoding:(/encoding/[^/]+?)?}")
public Response getUser(
@PathParam("id") int id,
@PathParam("format") String format,
@PathParam("encoding") String encoding) {
//your code
}
Now if you format and encoding will be optional. You you do not give any value they will be empty.
现在,如果您格式化和编码将是可选的。你你不给任何值他们就会是空的。
回答by cassiomolin
Rearrange the params and try the following:
重新排列参数并尝试以下操作:
@Path("/job/{param1}/{param2}{optional1 : (/optional1)?}{optional2 : (/optional2)?}")
public Response myMethod(@PathParam("param1") String param1,
@PathParam("param2") String param2,
@PathParam("optional1") String optional1,
@PathParam("optional2") String optional2) {
...
}
回答by Jorn
It might be easier to turn the optional path parameters into query parameters. You can then use @DefaultValue
if you need it:
将可选路径参数转换为查询参数可能更容易。@DefaultValue
如果需要,您可以使用:
@GET @Path("/job/{param1}/{param2}")
public Response method(@PathParam("param1") String param1,
@PathParam("param2") String param2,
@QueryParam("optional1") String optional1,
@QueryParam("optional2") @DefaultValue("default") String optional2) {
...
}
You can then call it using /job/one/two?optional1=test
passing only the optional parameters you need.
然后,您可以使用/job/one/two?optional1=test
仅传递您需要的可选参数来调用它。