Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

spring - How to set values as optional for QueryParam for rest api call in java

Would like to know how to set queryParam values as @Optional for @QueryParam.

Tried the following

@QueryParam("x") int x

I want to set a defaultvalue for x and make it as optional.

I tried the following ways

@QueryParam("x") @DefaultValue("1") int x

But when I pass empty in

http://localhost:8100/sort/values?x=

My expectation is to get the value of x as 1 because as I am setting the @DefaultValue("1")

But I am getting the below error

Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException

Because the @DefaultValue only accepts String and I am expecting a int datatype

Is there a way I can set a defaultValue and make it as optional for @QueryParam I can do this for RequestHeader but facing issues when I want the same kind of implementation for QueryParam

Please let me know if I am missing anything or any different kind of implementation.

question from:https://stackoverflow.com/questions/65887944/how-to-set-values-as-optional-for-queryparam-for-rest-api-call-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If using Spring as the tag suggest, you can try:

@RequestParam(required = false) String myParam

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...