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

Case Analysis of springboot validation Parameter Calibration

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "case analysis of springboot validation parameter verification". In daily operation, I believe that many people have doubts about the case analysis of springboot validation parameter verification. The editor has consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "case analysis of springboot validation parameter verification". Next, please follow the editor to study!

For any application, the data validity verification done on the client side is not safe and effective, so it requires us to verify the validity of the data on the server side during development. Spring Boot itself has a good support for the verification of data on the server side, and it can verify the validity of the data we submit to the server according to our prior agreement.

1 pom dependency

Org.springframework.boot spring-boot-starter-validation

2 check the use example

Configure the request entity to validate

Public class User {@ Null private Long id; @ NotBlank private String name; @ Email private String email; / / omitting getter and setter}

Controller method configuration

PostMapping ("/ addUser") public String addUser (@ Valid @ RequestBody User user) {.}

Unified handling of verification failure

A MethodArgumentNotValidException exception will be thrown when the verification fails

/ * * Global Exception processing * * @ author liusq * * / @ RestControllerAdvicepublic class GlobalExceptionHandler {private static final Logger LOGGER = LoggerFactory.getLogger (GlobalExceptionHandler.class); @ SuppressWarnings ("rawtypes") @ ExceptionHandler (value = Exception.class) public ResponseEntity handle (Exception e) {if (e instanceof MethodArgumentNotValidException) {BindingResult bindingResult = (MethodArgumentNotValidException) e). GetBindingResult (); if (bindingResult.hasErrors () & bindingResult.hasFieldErrors ()) {FieldError fieldError = bindingResult.getFieldError () BodyValidStatus bodyValidStatus = new BodyValidStatus.Builder (). Code ("0009") .message (fieldError.getDefaultMessage ()) .field (fieldError.getField ()). Build (); LOGGER.warn (bodyValidStatus.getMessage () + e); return new ResponseEntity (bodyValidStatus, HttpStatus.OK);} else {bodyStatus = DataUtil.bodyStatus ("0009");} else {bodyStatus = DataUtil.bodyStatus (Constants.ERROR_CODE);} LOGGER.error (bodyStatus.getMessage () + e); return new ResponseEntity (bodyStatus, HttpStatus.OK) } public class BodyValidStatus {/ / error code private String code; / / error code interpretation private String message; / / error field private String field; public BodyValidStatus () {} public BodyValidStatus (String code, String message, String field) {this.code = code; this.message = message; this.field = field;} private BodyValidStatus (Builder builder) {setCode (builder.code); setMessage (builder.message); setField (builder.field);} public String getCode () {return code } public void setCode (String code) {this.code = code;} public String getMessage () {return message;} public void setMessage (String message) {this.message = message;} public String getField () {return field;} public void setField (String field) {this.field = field;} @ Override public String toString () {return ToStringBuilder.reflectionToString (this);} public static final class Builder {private String code; private String message; private String field Public Builder () {} public Builder code (String val) {code = val; return this;} public Builder message (String val) {message = val; return this;} public Builder field (String val) {field = val; return this;} public BodyValidStatus build () {return new BodyValidStatus (this);}}

3 verify the detailed notes

Validate comments

Validated data type

Description

Null check

@ Null

Any type

Verify that the element value of the annotation is null

@ NotNull

Any type

Verify that the element of the annotation is not null

@ NotBlank

Charsequence subtype (CharBuffer, String, StringBuffer, StringBuilder)

Verify that the element value of the annotation is not empty (not null, and the length is not 0 after removing leading and trailing spaces), unlike @ NotEmpty,@NotBlank, which only applies to strings and removes leading and trailing spaces when comparing.

@ NotEmpty

CharSequence subtype, Collection, Map, array

Verify that the element value of the annotation is not null and is not empty (string length is not 0, collection size is not 0)

Boolean check

@ AssertFalse

Boolean,boolean

Verify that the element value of the annotation is false

@ AssertTrue

Boolean,boolean

Verify that the element value of the annotation is true

Length check

@ Size (min= lower limit, max= upper limit)

String, Collection, Map, array, etc.

Verify that the element value of the annotation is within the specified range of min and max (inclusive), such as character length and set size.

@ Length (min= lower limit, max= upper limit)

CharSequence subtype

Verify that the element value length of the annotation is within the interval of min and max

Date check

@ Past

Date type of the java.util.Date,java.util.Calendar;Joda Time class library

Verify that the element value (date type) of the annotation is earlier than the current time

@ Future

Same as @ Past requirement

Verify that the element value (date type) of the annotation is later than the current time

Numerical check

@ MIN (value= value)

BigDecimal,BigInteger, byte,short, int, long, etc. Any Number or CharSequence (which stores numbers) subtypes

Verify that the element value of the annotation is greater than or equal to the value specified by @ Min

@ MAX (value= value)

Same as @ Min requirement

Verify that the element value of the annotation is less than or equal to the value specified by @ Max

@ DecimalMin (value= value)

Same as @ Min requirement

Verify that the element value of the annotation is greater than or equal to the value specified by @ DecimalMin

@ DecimalMax (value= value)

Same as @ Min requirement

Verify that the element value of the annotation is less than or equal to the value specified by @ DecimalMax

@ Digits (integer= integer places, fraction= decimal places)

Same as @ Min requirement

Verify the upper limit of the integer and decimal places of the element value of the annotation

@ Range (minimum min=, maximum max=)

BigDecimal,BigInteger,CharSequence, byte, short, int, long and other atomic types and packaging types

Verify that the element value of the annotation is between the minimum and maximum values

Other inspection

@ Valid

Any non-atomic type

Specify the object associated with recursive verification; if there is an address object property in the user object, if you want to validate the address object together, add the @ Valid annotation to the address object to cascade the verification.

@ Pattern (regexp= regular expression, the pattern of the flag= flag)

Subtypes of CharSequence

Verify that the element value of the annotation matches the specified regular expression

@ Email (regexp= regular expression, the pattern of the flag= flag)

Subtypes of CharSequence

Verify that the element value of the annotation is Email, or you can specify a custom email format through regexp and flag

@ CreditCardNumber

Subtypes of CharSequence

Verify that the value of the annotation element is the credit card number

@ ScriptAssert (lang=, script=)

Business class

Verify complex business logic

4 Custom validation annotations and validation rules

Import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import javax.validation.Constraint;import javax.validation.Payload;import com.xxx.xxx.constraint.impl.MoneyValidator;@Target ({ElementType.FIELD, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Constraint (validatedBy=MoneyValidator.class) public @ interface Money {String message () default "not in the form of amount"; Class [] groups () default {}; 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