Java 你能在球衣里有一个可选的 QueryParam 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32363276/
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
Can you have an optional QueryParam in jersey?
提问by Rolando
Using java jersey, I have the following @QueryParam's in my method handler:
使用 java jersey,我的方法处理程序中有以下@QueryParam:
@Path("/hello")
handleTestRequest(@QueryParam String name, @QueryParam Integer age)
I know if I do: http://myaddress/hello?name=something
我知道如果我这样做: http://myaddress/hello?name=something
It will go into that method....
它将进入那个方法......
I want to make it so that I can call:
我想这样做,以便我可以打电话:
And it will also go into that same method. Is there any way I can flag an "optional" PathParam? Does it work with @FormParam too? Or am I required to create a separate method with a different method signature?
它也将采用相同的方法。有什么方法可以标记“可选”PathParam?它也适用于@FormParam 吗?或者我是否需要使用不同的方法签名创建一个单独的方法?
采纳答案by rafikn
In JAX-RS parameters are not mandatory, so if you do not supply an age value, it will be NULL
, and your method will still be called.
在 JAX-RS 中,参数不是强制性的,因此如果您不提供年龄值,它将是NULL
,并且您的方法仍将被调用。
You can also use @DefaultValue
to provide a default age value when it's not present.
您还可以使用@DefaultValue
来提供不存在的默认年龄值。
The @PathParam
parameter and the other parameter-based annotations, @MatrixParam
, @HeaderParam
, @CookieParam
, and @FormParam
obey the same rules as @QueryParam
.
该@PathParam
参数和其他基于参数的注解,@MatrixParam
,@HeaderParam
,@CookieParam
,并@FormParam
遵守相同的规则@QueryParam
。
回答by rgettman
You should be able to add the @DefaultValue
annotation the age
parameter, so that if age
isn't supplied, the default value will be used.
您应该能够为参数添加@DefaultValue
注释age
,以便如果age
未提供,将使用默认值。
@Path("/hello")
handleTestRequest(
@QueryParam("name") String name,
@DefaultValue("-1") @QueryParam("age") Integer age)
According to the Javadocs for @DefaultValue
, it should work on all *Param annotations.
根据Javadocs for@DefaultValue
,它应该适用于所有 *Param 注释。
Defines the default value of request meta-data that is bound using one of the following annotations: PathParam, QueryParam, MatrixParam, CookieParam, FormParam, or HeaderParam. The default value is used if the corresponding meta-data is not present in the request.
定义使用以下注释之一绑定的请求元数据的默认值:PathParam、QueryParam、MatrixParam、CookieParam、FormParam 或 HeaderParam。如果请求中不存在相应的元数据,则使用默认值。
回答by charlie_pl
You can always wrap return type in optional, for example: @QueryParam("from") Optional<String> from
您始终可以将返回类型包装在可选中,例如: @QueryParam("from") Optional<String> from