使用@Valid 表单验证

  1. 在domain层的数据表 class里面需要验证的数据加上验证条件
  2. 在Controller层参数前面添加@Valid注解

    doamin文件

  1. package com.example.luckymoney.domain;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.Id;
  5. import javax.validation.constraints.Min;
  6. import java.math.BigDecimal;
  7. /**
  8. * luckymoney 数据表
  9. */
  10. @Entity
  11. public class Luckymoney {
  12. @Id
  13. @GeneratedValue
  14. private Integer id;
  15. @Min(value = 10, message = "红包大小不能低于十元")
  16. private BigDecimal money;
  17. /**
  18. * 红包发送方
  19. */
  20. private String producer;
  21. public BigDecimal getMoney() {
  22. return money;
  23. }
  24. public void setMoney(BigDecimal money) {
  25. this.money = money;
  26. }
  27. public String getProducer() {
  28. return producer;
  29. }
  30. public void setProducer(String producer) {
  31. this.producer = producer;
  32. }
  33. }

controller使用

  1. package com.example.luckymoney.controller;
  2. import com.example.luckymoney.repository.LuckmoneyRepository;
  3. import com.example.luckymoney.domain.Luckymoney;
  4. import com.example.luckymoney.service.LuckymoneyService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.validation.BindingResult;
  7. import org.springframework.web.bind.annotation.*;
  8. import javax.validation.Valid;
  9. import java.math.BigDecimal;
  10. import java.util.List;
  11. import java.util.Optional;
  12. @RestController
  13. public class LuckymoneyController {
  14. @Autowired
  15. private LuckmoneyRepository repository;
  16. @Autowired
  17. private LuckymoneyService service;
  18. /**
  19. * 获取红包列表
  20. */
  21. @GetMapping("/luckymoneys")
  22. public List<Luckymoney> list() {
  23. return repository.findAll();
  24. }
  25. /**
  26. * 添加一个红包
  27. */
  28. @PostMapping("/luckymoney")
  29. public Luckymoney create(@Valid Luckymoney luckymoney, BindingResult bindingResult) {
  30. // bindingResult返回验证的结果
  31. if (bindingResult.hasErrors()) {
  32. System.out.println(bindingResult.getFieldError().getDefaultMessage());
  33. return null;
  34. }
  35. luckymoney.setProducer(luckymoney.getProducer());
  36. luckymoney.setMoney(luckymoney.getMoney());
  37. return repository.save(luckymoney);
  38. }
  39. }