0

I'm receiving a path parameter called id in a get method in my controller as an integer. When the controller receives it it obviously casts the incoming string parameter called id to an integer. But if I leave the id field empty when I call the controller I get a 400 Bad Request since it can't cast an empty string to an integer. Is there any way around this? I need it to be an integer so I can do a check that the id value is a positive integer ie id > 0.

Anyone?

  • [Spring Optional Path Variables (Baeldung)](https://www.baeldung.com/spring-optional-path-variables) – Turing85 Jun 04 '21 at 22:21

1 Answers1

0

Sample logic to solve your problem could be like this:

private static final String PATTERN = "^-?+\\d+\\.?+\\d*$";

@GetMapping("/pathName")
public <T> methodName(@RequestParam(value ="valName") String val){
  
  int valueRetrieved = 0;
  if(!val.equals("null") || val.isEmpty() || val.matches(PATTERN)){
      valueRetrieved = Integer.parseInt(val);
  }
  
  //use **valueRetrieved to perform your computational logics**

}
  • The logic has a major flaw. If `val` is `null`, a `NullpointerException` will be thrown. – Turing85 Jun 04 '21 at 23:30
  • //doSomething, implies, you can handle errors, using a customized class extending **RuntimeException** annotated with **@ResponseSatus(HttpStatus.[ERROR_NAME)** to handle error responses to the user @Turing85 – RoundedHouse Jun 05 '21 at 07:25
  • `//doSomethiing here` will not be reached in the case I have described. The problem can be avoided if the conditions in the `if`-clause are reordered. – Turing85 Jun 07 '21 at 17:27
  • well noted and have made the necessary corrections thanks @Turing85 – RoundedHouse Jun 12 '21 at 11:49
  • ... this will still throw a `NullPointerException` if `val` is `null`. – Turing85 Jun 13 '21 at 12:02