Java 未指定 @DefaultValue 时,@QueryParam 的默认值是什么?

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

What are the default values for @QueryParam when @DefaultValue is not specified?

javarestjavax.ws.rsqueryparam

提问by AlikElzin-kilaka

For example, having the following Java rest definition:

例如,具有以下 Java rest 定义:

@GET
@Path("/something")
public String somthing(
    @QueryParam("valString") String valString,
    @QueryParam("valInt") int valInt,
    @QueryParam("valBool") boolean valBool
) {
  ...
}

And invocation:

并调用:

curl -X GET 127.0.0.1/something

What will the parameters values be if not specified in the invocation? (valString=?, valInt=?, valBool=?)

如果未在调用中指定,参数值将是什么?(valString=?, valInt=?, valBool=?)

采纳答案by cassiomolin

Short answer

简答

The parameter values will be:

参数值将是:

  • valString: null
  • valInt: 0
  • valBool: false
  • valStringnull
  • valInt0
  • valBoolfalse

A bit longer answer

有点长的答案

Quoting the Java EE 7 tutorialabout extracting request parameters:

引用有关提取请求参数Java EE 7 教程

If @DefaultValueis not used in conjunction with @QueryParam, and the query parameter is not present in the request, the value will be an empty collection for List, Set, or SortedSet; nullfor other object types; and the default for primitive types.

如果@DefaultValue在与结合不使用@QueryParam,且查询参数不存在于该请求,则该值将是一个空集ListSetSortedSet; null对于其他对象类型;和原始类型的默认值。

The default values for primitive types are described in the Java Tutorialsfrom Oracle:

Oracle的Java 教程中描述了原始类型的默认值:

 Primitive       Default Value
-------------------------------
 byte            0
 short           0
 int             0
 long            0L
 float           0.0f
 double          0.0d
 char            '\u0000'
 boolean         false

As you already know, this behavior can be changed by using the @DefaultValueannotation as following:

正如您已经知道的那样,可以通过使用以下@DefaultValue注释来更改此行为:

@GET
@Path("/foo")
public String myMethod(@DefaultValue("foo") @QueryParam("valString") String valString,
                       @DefaultValue("1") @QueryParam("valInt") int valInt,
                       @DefaultValue("true") @QueryParam("valBool") boolean valBool) {
    ....
}

回答by francesco foresti

the values will be null, 0, false, i.e. the default values for non-initialized variables of those types. If the client does not put the parameters in the URL and the service does not specify default values, what the service will get are Java default values for non-initialized variables.

这些值将是null, 0, false,即这些类型的未初始化变量的默认值。如果客户端没有在 URL 中放入参数,并且服务没有指定默认值,那么服务将获得的是未初始化变量的 Java 默认值。