Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize super-flexible annotated data check by Spring boot

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to achieve super-flexible annotated data checking in Spring boot". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to achieve super-flexible annotated data checking by Spring boot".

Through the section, the ultra-flexible annotated data check is realized.

In the development of enterprise systems, the scene of user form input is often encountered. How to make data validation separate from the business code logic, no one wants to judge the fields one by one in the logic code.

The check mode of Spring MVC

When using Spring MVC, use hibernate-validator 's annotations directly, as follows:

Public class User {private Long id; @ NotBlank (message = "name cannot be empty") @ Size (min = 5, max = 10, message = "5 to 10 characters") private String name; private String des; @ NotNull @ Max (value = 3, message = "type parameter error") @ Min (value = 0, message = "type parameter error") private Integer type @ Min (value = 0, message = "Parameter error, limit must be greater than or equal to 0") private int limit; @ Pattern (regexp = "^ (true | false) $", message = "Parameter error, parameter isActive can only be true or false") private String flag; / / setters and getters

Then take the User object as the parameter of Controller and give it to Spring MVC to verify it for you.

Realize one's own annotated data check through section

This is a SOA micro-service application without controller and Spring MVC, and of course there are no so-called containers (Tomcat, Jetty). Parameter verification is also required for calls from client. Continue to be based on hibernate-validator

Refer to the official documentation of validator

Introduce dependencies:

Org.hibernate hibernate-validator-cdi 5.4.1.Final org.glassfish javax.el 3.0.1-b08

Here you need to introduce some knowledge points of spring boot and aop, and go to google on your own. I went straight to the code, who told me to be the porter of the code.

Define a section:

@ Aspect / / an aspect @ Configuration / / spring boot configuration class public class RequestParamValidAspect {private final ValidatorFactory factory = Validation.buildDefaultValidatorFactory (); private final ExecutableValidator methodValidator = factory.getValidator (). ForExecutables (); private final Validator beanValidator = factory.getValidator (); private Set validMethodParams (T obj, Method method, Object [] params) {return methodValidator.validateParameters (obj, method, params);} private Set validBeanParams (T bean) {return beanValidator.validate (bean) } @ Pointcut ("execution (* com.jiaobuchong.commodity.service.*.* (..)") Public void soaServiceBefore () {} / * * cut into * / @ Before ("soaServiceBefore ()") public void twiceAsOld1 (JoinPoint point) {/ / get the target object Object target = point.getThis () through the join point; / / get the parameter Object [] args = point.getArgs () / / get the cut-in method Method method = ((MethodSignature) point.getSignature ()). GetMethod (); / / verify Set validResult = validMethodParams (target, method, args) with basic data types as method parameters; Iterator violationIterator = validResult.iterator () While (violationIterator.hasNext ()) {/ / here you can throw an exception to prompt the user that the input of the parameter is not in the correct format System.out.println ("method check-" + violationIterator.next () .getMessage ()) } / / verify for (Object bean: args) {if (null! = bean) {validResult = validBeanParams (bean); violationIterator = validResult.iterator () While (violationIterator.hasNext ()) {/ / here you can throw an exception to prompt the user that the input format of the parameter is incorrect System.out.println ("bean check-" + violationIterator.next () .getMessage ());}

Specific Service

/ / DemoService.javapublic interface DemoService {void one (@ NotNull (message = "cannot be null") Integer a, @ NotBlank String b); void two (@ NotNull (message = "paramsVo cannot be null") ParamsVo paramsVo, @ NotNull (message = "go cannot be null") String go);} / / ParamsVo.javapublic class ParamsVo {@ NotBlank (message = "cannot be empty") private String name @ NotBlank @ Length (min = 2, max = 20, message = "cannot be empty, up to 20 words") private String desc; @ NotNull @ Valid / / needs to be annotated with @ Valid, otherwise the Img object private List will not be verified

ImgList; @ NotNull (message = "length cannot be null") @ Range (min = 3, max = 100, message = "length range 3-100") private Integer length; / / omitted other code} public class Img {@ NotNull (message = "img id cannot be null") private Long id; @ NotBlank (message = "img name cannot be empty") private String name; / / omitted other code}

Run DemoService:

@ Autowired private DemoService demoService; @ Test public void testGo () {demoService.one (null, "); ParamsVo paramsVo = new ParamsVo (); List

List = new ArrayList (); Img img = new Img (); list.add (img); paramsVo.setImgList (list); paramsVo.setDesc ("you"); paramsVo.setLength (1); demoService.two (paramsVo, null);}

Running result:

Method check--- cannot be empty

Method check--- cannot be null

Method check---go cannot be null

Bean check---img name cannot be empty

Bean check--- cannot be empty

Bean check--- depth range 3-100

Bean check---img id cannot be null

Bean check--- cannot be empty, up to 20 words

This is more powerful than the check function of Spring MVC.

/ / void one (@ NotNull (message = "cannot be null") Integer a, @ NotBlank String b) has no effect on the following check in Spring MVC

After some transformation, everything is supported. And independent of business logic, maintenance and new checks are very convenient, the amount of code is also less!

Spring boot aop annotation data permission verification annotation class @ Retention (RetentionPolicy.RUNTIME) public @ interface DataAuthValid {/ / location public int index () default 0; / / field id / / public String id () default "id"; / / field id public String orgId () default "org_id"; / / mapper @ SuppressWarnings ("rawtypes") public Class

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report