@QueryParam如何将没有值的参数转换为布尔值"false"? [英] How can @QueryParam translate a parameter without value to boolean "false"?
问题描述
我想使用类似http://www.example.com/rest/foo?bar
的URL,其中bar
查询参数没有值,仅它的存在就应该表示变量是true
还是false
.
I'd like to use an URL like http://www.example.com/rest/foo?bar
where the bar
query parameter has no value and its presence alone should denote if a variable is true
or false
.
当前,缺失值假定为""
(空),并传递给new Boolean()
,后者将其视为false
.
Currently the missing value is assumed to be ""
(empty) and passed to new Boolean()
which treats it as false
.
是否有比定义参数为String自己转换的方法更优雅的定义方式?
Is there a more elegant way of defining it than declaring the parameter to be String and converting it myself?
例如javax.rs.BooleanFlag
或类似的课程?
推荐答案
您可以尝试以下操作:
@GET
@Path("/some-path")
public Response myMethod(@Context HttpServletRequest request) {
boolean isParameterPresent = request.getParameterMap().contains("bar");
...
}
但是 peeskillet的答案中显示的解决方案是实现此目的的最聪明的方法.
But the solutions shown in peeskillet's answer are the cleverest ways to achieve it.
这篇关于@QueryParam如何将没有值的参数转换为布尔值"false"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!