0

I have a rest API where I need to send page num as query parameter. When I send null, it gives me a bad request. Below is the rest API code

@RequestMapping(value = "/sample", method = RequestMethod.GET) @ResponseBody public String sample( @RequestParam(value = "page-number", required = false, defaultValue = "1") final Integer pageNumber, @RequestParam(value = "page-size", required = false, defaultValue = "50") final Integer pageSize) { return "hello"; } 

I am hitting the API with the following URL http://localhost:8000/sample?pageNumber=null

I am getting the below exception

"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"null\"", 

How do I handle null case?

8
  • 3
    Rather than attempting to pass null, just remove the parameter from the URL . Commented Feb 27, 2018 at 13:09
  • 1
    The Exception is clearly saying what the problem is. Commented Feb 27, 2018 at 13:09
  • why do you want to send null? Commented Feb 27, 2018 at 13:09
  • localhost:8000/sample should be your URL.. Commented Feb 27, 2018 at 13:10
  • I have understood the exception,that it is because of null being considered as string but how do I handle it,if in case it is passed? @MehrajMalik Commented Feb 27, 2018 at 13:10

1 Answer 1

2

While hitting any HTTP request, if you don't want to send any value of any request parameter, then please don't include that specific parameter in URL instead of sending null value to that parameter.

For e.g. If you don't want to send any value in pageNumber request parameter, then please don't include pageNumber in request parameter. So your request URL will be: http://localhost:8000/sample

If you will hit URL something like http://localhost:8000/sample?pageNumber=null, then it will map "null" string literal to pageNumber request param, and you will get following exception:

"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"null\"",

because you are expecting an Integer value that should be mapped with pageNumber request parameter not a string literal.

Sign up to request clarification or add additional context in comments.

1 Comment

And How to handle with wrong parameter name? can it be catch with a predefined exceptions and handled accordingly?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.