java Spring API布尔参数严格验证

jdg4fx2g  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(138)

我希望对一个布尔参数执行严格的验证,如下所示为“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接受这个值的非布尔替换,比如0/1。这显然是设计好的,如下所述:https://stackoverflow.com/a/25123000/11994829
但是,我想严格地只允许在请求中使用“true/false”,那么我可以在将参数定义为布尔值的同时做到这一点吗?

nuypyhwy

nuypyhwy1#

尝试创建您自己的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 + "'");
    }
}

相关问题