spring annotation validation @NotNull and other usage methods

Keywords: less Java Hibernate Spring

Commonly used labels

@ Null annotated element must be null
 @ NotNull annotated element cannot be null
 @ The annotated element of AssertTrue must be true
 @ AssertFalse annotated elements must be false
 @ The annotated element of Min(value) must be a number whose value must be greater than or equal to the specified minimum.
@ The annotated element of Max(value) must be a number whose value must be less than or equal to the specified maximum.
@ DecimalMin(value) annotated elements must be a number whose value must be greater than or equal to the specified minimum
 @ DecimalMax(value) annotated elements must be a number whose value must be less than or equal to the specified maximum
 @ The size of Size(max,min) annotated elements must be within the specified range.
@ The commented element of Digits(integer,fraction) must be a number whose value must be acceptable.
@ Past annotated elements must be a past date
 @ The annotated element of Future must be a future date
 @ The annotated element of Pattern(value) must conform to the specified regular expression.
@ Email annotated elements must be e-mail addresses
 @ Length's annotated string size must be within the specified range
 @ NotEmpty annotated strings must be non-empty
 @ Range annotated elements must be within the appropriate scope

example :
Validation of data from vo pages
inferface: Just as a tag, a group can add more than one group to a field validated by vo, so that a group that does not join will not validate the field
controller: You need to add @Validated (GroupInterface1. class)//GroupInterface1. Class is defined as GroupInterface2. Fields that need to be verified by class will not be validated.

VO:

public class User implements Serializable {
    /**
     * Primary key
     */
    @NotNull(message = "primary is not null",groups = {GroupInterface1.class})
	private Long id;
	
	@Pattern(regexp = "[0123456789]",groups = {GroupInterface1.class,GroupInterface2.class},message = "hava a error Date")
	private Long maxDiscountAmount;
	

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	private Date createTime;

	@Future(message = "expireTime is not less than now",groups = {GroupInterface1.class,GroupInterface2.class})
	@NotNull(message = "expireTime is not null",groups = {GroupInterface1.class,GroupInterface2.class})
	private Date expireTime;

}

Another example:

import java.util.Date;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Email;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;

/**** imports ****/
public class ValidatorPojo {

	// Non empty judgement
	@NotNull(message = "id Can not be empty")
	private Long id;

	@Future(message = "Need a future date") // Only the future date
	// @ Past // Past dates only
	@DateTimeFormat(pattern = "yyyy-MM-dd") // Date formatting conversion
	@NotNull // Can not be empty
	private Date date;

	@NotNull // Can not be empty
	@DecimalMin(value = "0.1") // Minimum value 0.1 yuan
	@DecimalMax(value = "10000.00") // Maximum 10000 yuan
	private Double doubleValue = null;

	@Min(value = 1, message = "Minimum value is 1") // Minimum value is 1
	@Max(value = 88, message = "The maximum value is 88.") // Max 88
	@NotNull // Can not be empty
	private Integer integer;

	@Range(min = 1, max = 888, message = "Scope 1 to 888") // Limited scope
	private Long range;

	// Mailbox validation
	@Email(message = "Error in mailbox format")
	private String email;

	@Size(min = 20, max = 30, message = "String length is between 20 and 30.")
	private String size;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Double getDoubleValue() {
		return doubleValue;
	}

	public void setDoubleValue(Double doubleValue) {
		this.doubleValue = doubleValue;
	}

	public Integer getInteger() {
		return integer;
	}

	public void setInteger(Integer integer) {
		this.integer = integer;
	}

	public Long getRange() {
		return range;
	}

	public void setRange(Long range) {
		this.range = range;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getSize() {
		return size;
	}

	public void setSize(String size) {
		this.size = size;
	}

	/**** setter and getter ****/

}

At this point, the controller should add @Valid, otherwise it will not be validated!

/***
	 * Error in parsing validation parameters
	 * @param vp —— POJO that needs to be validated, using annotation @Valid to represent validation
	 * @param errors  Error message, which is automatically populated by Spring MVC after verifying POJO
	 * @return Error message Map
	 */
	@RequestMapping(value = "/valid/validate")
	@ResponseBody
	public Map<String, Object> validate(
	        @Valid @RequestBody ValidatorPojo vp, Errors errors) {
	    Map<String, Object> errMap = new HashMap<>();
	    // Get the error list
	    List<ObjectError> oes = errors.getAllErrors();
	    for (ObjectError oe : oes) {
	        String key = null;
	        String msg = null;
	        // Field error
	        if (oe instanceof FieldError) {
	            FieldError fe = (FieldError) oe;
	            key = fe.getField();// Get the error validation field name
	        } else {
	            // Non-field error
	            key = oe.getObjectName();// Get the name of the validation object
	        }
	        // error message
	        msg = oe.getDefaultMessage();
	        errMap.put(key, msg);
	    }
	    return errMap;
	}

GROUP interface (grouping)

Posted by rostislav on Fri, 10 May 2019 13:13:35 -0700