spring文章精选程序员Spring Boot

SpringMVC: @Valid 表单验证

2017-12-20  本文已影响348人  聪明的奇瑞

使用例子

假设我们有一个 Student 实体类

@Entity
@Table(name = "Student")
@Data
public class Student {
    @Id
    @GeneratedValue
    private Integer id;

    @NotEmpty(message = "姓名不能为空!")
    @Column(length = 50)
    private String name;

    @NotNull(message = "年龄不能为空!")
    @Min(value = 18, message = "年龄必须大于18岁!")
    @Column(length = 50)
    private Integer age;
}

Dao 接口

public interface StudentRepository extends JpaRepository<Student,Integer> {}
      ○ Service 接口:
public interface StudentService {
    void add(Student student);
}

Service 接口实现类

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void add(Student student) {
        studentRepository.save(student);
    }
}

Controller

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @PostMapping(value="/add")
    public String add(@Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return bindingResult.getFieldError().getDefaultMessage();
        }else{
            studentService.add(student);
            return "添加成功!";
        }
    }
}

校验注解

空检查

Boolean检查

长度检查

日期检查

数值检查

其它检查

上一篇 下一篇

猜你喜欢

热点阅读