0

I wish to perform strict validation on a boolean parameter, seen below as "withDetails."

   @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Success")})
    @GetMapping(value = "/order", produces = "application/json")
    public ResponseEntity<ResponseClass> getOrders( String id,
            @RequestParam(value = "withDetails", defaultValue = "true")
            Boolean withDetails){
        ResponseClass responseClass = this.service.getResponse(id, withDetails);
        return ResponseEntity.ok(responseClass);
    }

Spring accepts non-boolean substitutions for this value, such as 0/1. This is apparently by design, as described here: https://stackoverflow.com/a/25123000/11994829

However, I want to strictly only allow "true/false" in requests. Can I do that while still defining the parameter as Boolean?

scoll
  • 117
  • 1
  • 15

2 Answers2

1

Try to create your own Converter:

@Component
public class BooleanConverter implements Converter<String, Boolean> {

    @Override
    public Boolean convert(String bool) {
        if ("true".equals(bool)) {
            return true;
        }
        if ("false".equals(bool)) {
            return false;
        }
        throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
    }
}
dey
  • 3,022
  • 1
  • 15
  • 25
  • This successfully parses the argument and throws IllegalArgumentException. Unfortunately, this subsequently gets caught by ConversionUtils.invokeConverter, which throws ConversinFailedException, which in turn gets caught by TypeConverterDelegate.convertIfNecessary. I want to keep the IllegalArgumentException up the stack so the endpoint can return the error. – scoll Jan 10 '23 at 17:29
  • 1
    It's hard to tell without debugging the code, but there is a throw at the end of `convertIfNecessary` method, you can try to debug this method and see what should be done to throw this exception in such a case. Maybe the problem is because of defaultValue for this param? – dey Jan 11 '23 at 17:53
0

In spring Boolean parameters have a value of 1/0 if you want to catch the value boolean type make parameter as String String withDetails and convert it .valueOf into boolean type (true\false) or you to make your own converter convert 1 as true and 0 as false