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?
CodePudding user response:
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 "'");
}
}
CodePudding user response:
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