spring boot used in the form validation

I. Introduction

Verification for the wisdom to engage in this form it? The answer is simple and realistic, For chestnuts, you worked so hard to write a function entry of personal information, such as age this position, the user no see once wrote a male gender, submit a direct error, it is not it is very embarrassing,

As a test of the students, I would like to say is that really the user's behavior is unpredictable, still add it.

Second, the simulation scenarios

I remember I was in school that would be, under eighteen years of age are not allowed to go to Internet cafes, until college, starting identity card, just let go, helpless ah, the bedroom of a network card too ~~~~~

So now we have the analog age 18 and older classmate to go to the Internet cafe. Below we will verify with examples to illustrate the use of the form.

1, modify the interface to new students

The transfer field value, Student object to pass, the following sample code:

/**
     * 新增一个学生
     *
     * @return
     */
    @PostMapping("/studentAdd")
    public Student sudentAdd(@Valid Student student, BindingResult bindingResult) {
        if(bindingResult.hasFieldErrors()){
            //输出错误信息
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        student.setName(student.getName());
        student.setAge(student.getAge());
        student.setSex(student.getSex());
        student.setEmail(student.getEmail());
        //Maintaining and updating both the method by 
        return studentResponstory.save (Student); 
    }

2, add the restriction on the entity object

@MIN used to limit the minimum input, a specific example of code is as follows:

package com.rongrong.springboot.demo.domain;


import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/30 21:24
 */
@Entity
@Data
public class Student {

    //主键ID
    @Id
    //自增型
    @GeneratedValue
    private Integer id;
    Private String name; 
    @min (value = 18, the Message = "under 18 years of age, not identity, not to Internet cafes!" )
     Private Integer Age;
     Private String Sex;
     Private String Email;
     public Student () { 
    } 
}

3, start the service

Call interface, adding a greater than 18-year-old student, was as follows:

 

 Again amend, modify age of 2 years old, again call interface, postman returned empty results are as follows:

 

 Do we have a look at the console prompt:

 

 

This, with regard to verification form, introduction, interested students can try on their own.

Guess you like

Origin www.cnblogs.com/longronglang/p/12142247.html