Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use custom annotations to verify restful request parameters

Shulou Source: shulou.com Published: 2022-06-03 03:56:17 10月24日 Update

This article is about how to use custom annotations to validate restful request parameters. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Custom annotations for verification of restful request parameters

When developing with springmvc, we usually add annotations such as @ NotNull () to the method parameter entity class in controller, and then add

@ Vilad annotation, so that when there is a request, it will automatically check whether the parameter is legal according to our annotation, avoiding our manual verification.

However, sometimes the self-contained verification annotations can not meet our business verification needs, so it is necessary for us to customize the verification annotations and customize us according to the business requirements.

Your own verification notes.

Let's look at an example:

1. First, we use @ interface to define an annotation @ Target ({METHOD, FIELD, ANNOTATION_TYPE}) @ Retention (RUNTIME) @ Constraint (validatedBy = ByteLengthValidator.class) / / specify the annotation verification implementation class using @ Constraint. This is a restricted annotation and can only use the specified implementation class @ Documentedpublic @ interface ByteLength {int min () default 0; int max () default 2147483647; String charsetName () default "GBK". String message () default "can only be between {min} and {max}"; Class [] groups () default {}; Class

Tags: Annotations parameters interfaces methods time methods business content fields entities objects more articles rules requirements good legal practical necessary between Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL vpn MariaDB Microsoft Shulou Technology