天天看点

@Valid表单验证注解使用

表单验证在开发中用的非常多,接下来简单介绍基于Jpa的@Valid的使用。

写好实体类Girl,在age属性上用@Min注解value的值为18,也就是age>=18才能通过表单验证,message的值,在Controller层进行展示输入小于18的数,然后显示message信息。

package com.wg.girls.entity;

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

@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @Min(value = 18,message = "禁止未成年入内!!")
    private Integer age;//使用@Min注解让age的值不小于18,

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

           

在create方法有两个参数,在Girl前面注解@valid,也就是验证,验证的值就在BindingResult里面。通过result.hasErrors()返回一个boolean数据,true验证不通过,不通过的信息使用result.getFileErrors().getDefaultMessage();false验证通过。

package com.wg.girls.controller;

import com.wg.girls.dao.GirlDao;
import com.wg.girls.entity.Girl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by Administrator
 * 2020/3/19  18:03
 */
@RestController
public class GirlController {

    @Autowired
    private GirlDao dao;


    @GetMapping("/girls")
    public List<Girl> girls(){
        return dao.findAll();
    }

    @PostMapping("/girls")
    //@Valid注解进行验证girl的age,小于18 result.hasErrors的值为true,否则false。
    public Object create(@Valid Girl girl, BindingResult result){
            if(result.hasErrors()){
                //result.hasErrors 为true,验证不通过。getDefaultMessage()方法获取@Min里面的Message
                return result.getFieldError().getDefaultMessage();
            }
        return dao.save(girl);
    }
}

           

通过url http://localhost:8080/girls?name=小妹妹&age=12进行传参,girl对象会取出url里的对应名称给girl对象赋值。 girl.age=12表单验证不能通过。

@Valid表单验证注解使用

继续阅读