你能在球衣中有一个可选的 QueryParam 吗?

Can you have an optional QueryParam in jersey?

使用 java 球衣,我的方法处理程序中有以下 @QueryParam:

@Path("/hello")
handleTestRequest(@QueryParam String name, @QueryParam Integer age)

我知道如果我这样做: http://myaddress/hello?name=something

它将进入那个方法....

我想做,这样我就可以打电话给:

http://myaddress/hello?name=something

它也会进入同样的方法。有什么方法可以标记 "optional" PathParam?它也适用于 @FormParam 吗?或者我是否需要创建一个具有不同方法签名的单独方法?

您应该能够将 @DefaultValue 注释添加到 age 参数,这样如果未提供 age,将使用默认值。

@Path("/hello")
handleTestRequest(
    @QueryParam("name") String name,
    @DefaultValue("-1") @QueryParam("age") Integer age)

根据 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.

在 JAX-RS 中参数不是强制性的,因此如果您不提供年龄值,它将是 NULL,您的方法仍将被调用。

您还可以使用 @DefaultValue 提供默认年龄值(当它不存在时)。

@PathParam 参数和其他基于参数的注释 @MatrixParam@HeaderParam@CookieParam@FormParam 遵守与 @QueryParam

Reference

您始终可以将 return 类型包装成可选的,例如:@QueryParam("from") Optional<String> from