java @QueryParam 如何将没有值的参数转换为布尔值“false”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33258196/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:26:01  来源:igfitidea点击:

How can @QueryParam translate a parameter without value to boolean "false"?

javajax-rs

提问by lathspell

I'd like to use an URL like http://www.example.com/rest/foo?barwhere the barquery parameter has no value and its presence alone should denote if a variable is trueor false.

我想使用像一个URL http://www.example.com/rest/foo?bar,其中bar查询参数没有价值,它的单独存在应表示变量是否truefalse

Currently the missing value is assumed to be ""(empty) and passed to new Boolean()which treats it as false.

目前,缺失值被假定为""(空)并传递给new Boolean()将其视为false.

Is there a more elegant way of defining it than declaring the parameter to be String and converting it myself?

有没有比将参数声明为 String 并自己转换它更优雅的定义方式?

Like e.g. a class javax.rs.BooleanFlagor similar?

比如一个班级javax.rs.BooleanFlag或类似的?

采纳答案by cassiomolin

You could try the following:

您可以尝试以下操作:

@GET
@Path("/some-path")
public Response myMethod(@Context HttpServletRequest request) {

    boolean isParameterPresent = request.getParameterMap().contains("bar");

    ...
}

But the solutions shown in peeskillet's answerare the cleverest ways to achieve it.

但是peeskillet的答案中显示的解决方案是实现它的最聪明的方法。

回答by Phoste

I know it's an old question but I had the same trouble.

我知道这是一个老问题,但我遇到了同样的问题。

To solve my problem, I used the Annotation @DefaultValue :

为了解决我的问题,我使用了注解 @DefaultValue :

@GET
@Path("/path")
public Response myMethod(@DefaultValue("true") @QueryParam("foo") boolean foo) {
    if (foo) {
       ...
    }
}

So, when the request contains the parameter foothe boolean value will be false and if not it will be true. It shows the opposite of reality but if you're aware of it, it's quite simple to use.

因此,当请求包含参数时foo,布尔值将为 false,否则为 true。它显示了与现实相反的情况,但如果您意识到这一点,则使用起来非常简单。

回答by Paul Samsotha

Note:upon seeing Phoste's answer, I'd go with his/her solution. I'm leaving this answer up, as there is still some useful information here.

注意:在看到Phhoste 的回答后,我会采用他/她的解决方案。我要留下这个答案,因为这里仍然有一些有用的信息。

Is there a more elegant way of defining it than declaring the parameter to be String and converting it myself? Like e.g. a class javax.rs.BooleanFlagor similar?

有没有比将参数声明为 String 并自己转换它更优雅的定义方式?比如一个班级javax.rs.BooleanFlag或类似的?

No such type (BooleanFlag), If you look at the javadoc for @QueryParam, you'll see a list of options for how we can create a custom type to use a @QueryParamvalue (for the most part the same holds true for other @XxxParams also)

没有这样的类型 ( BooleanFlag),如果您查看@QueryParamjavadoc,您将看到有关如何创建自定义类型以使用@QueryParam值的选项列表(在大多数情况下,其他@XxxParams 也是如此)

  • Have a constructor that accepts a single String argument
  • Have a staticmethod named valueOfor fromStringthat accepts a single String argument (see, for example, Integer.valueOf(String))
  • Have a registered implementation of ParamConverterProviderJAX-RS extension SPI that returns a ParamConverterinstance capable of a "from string" conversion for the type.
  • 有一个接受单个 String 参数的构造函数
  • 有一个static名为valueOfor的方法fromString接受单个 String 参数(例如,请参见Integer.valueOf(String)
  • 拥有ParamConverterProviderJAX-RS 扩展 SPI的注册实现,该实现返回一个ParamConverter能够对该类型进行“从字符串”转换的实例。

So from the first option, in theory, you should be able to do something like

所以从第一个选项,理论上,你应该能够做类似的事情

public class Flag {

    private final boolean  isPresent;
    public Flag(String param) { isPresent = param != null; }
    public boolean isPresent() { return isPresent; }
}
@GET
public String get(@QueryParam("bar") Flag bar) {
    if (bar.isPresent()) {
        return "bar is present";
    } else {
        return "bar is not present";
    }
}

Now this works when the query flag is present. But when it's not, it acts like any other non-primitive type; it's null. So the call to bar.isPresentgive an NPE. Tested with a fromStringand valueOfwith the same result. We couldcheck if (bar == null), but that's no better that just using a String and checking if the String is null. It's not pretty.

现在这在查询标志存在时起作用。但是当它不是时,它的行为就像任何其他非原始类型;它是空的。所以打电话bar.isPresent给NPE。用 afromString和测试,valueOf结果相同。我们可以检查if (bar == null),但这并不比仅使用字符串并检查字符串是否为空更好。它不漂亮

So the last option is the ParamConverterProvider. Which does actually work. Below is the implementation.

所以最后一个选项是ParamConverterProvider. 这确实有效。下面是实现。

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;

@Provider
public class FlagParamConverterProvider implements ParamConverterProvider {

    @Override
    public <T> ParamConverter<T> getConverter(
            Class<T> rawType, Type genericType, Annotation[] annotations) {
        if (rawType != Flag.class) {
            return null;
        }

        return new ParamConverter<T>() {

            @Override
            public T fromString(String value) {
                return (T)new Flag(value);
            }

            @Override
            public String toString(T value) { return null; } 
        };
    }  
}

Just make sure the provider is registered. It's a pretty clean solution in my opinion.

只需确保提供者已注册。在我看来,这是一个非常干净的解决方案。