简体   繁体   中英

How to validate fields of request body in SpringBoot controllers (customize Jackson)

SpringBoot controller consumes @RequestBody that is a bean class, for example it's a class Basket with a list of fields. Some of these fields are read-only, and I want to throw an exception when user tries to send a request to update them.

I use custom @ReadOnly annotation to mark read-only fields of class Basket. I want to customize Jackson in a way when Jackson constructs object Basket - it should analyze bean with annotations and throw an exception when incoming JSON contains read only fields.

Please do not advice JSR-303 Bean Validation.

You can write your custom deserializer and can access annotations using the following code and write logic to throw exceptions.

for (Field f: Basket.class.getFields())     {  
               ReadOnly readOnly = f.getAnnotation(ReadOnly.class);  
               if (readOnly != null)  
                  // your logic can go here.  
              }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM