使用@Valid 表单验证
- 在domain层的数据表 class里面需要验证的数据加上验证条件
- 在Controller层参数前面添加@Valid注解
doamin文件
package com.example.luckymoney.domain;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.validation.constraints.Min;import java.math.BigDecimal;/** * luckymoney 数据表 */@Entitypublic class Luckymoney { @Id @GeneratedValue private Integer id; @Min(value = 10, message = "红包大小不能低于十元") private BigDecimal money; /** * 红包发送方 */ private String producer; public BigDecimal getMoney() { return money; } public void setMoney(BigDecimal money) { this.money = money; } public String getProducer() { return producer; } public void setProducer(String producer) { this.producer = producer; }}
controller使用
package com.example.luckymoney.controller;import com.example.luckymoney.repository.LuckmoneyRepository;import com.example.luckymoney.domain.Luckymoney;import com.example.luckymoney.service.LuckymoneyService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.math.BigDecimal;import java.util.List;import java.util.Optional;@RestControllerpublic class LuckymoneyController { @Autowired private LuckmoneyRepository repository; @Autowired private LuckymoneyService service; /** * 获取红包列表 */ @GetMapping("/luckymoneys") public List<Luckymoney> list() { return repository.findAll(); } /** * 添加一个红包 */ @PostMapping("/luckymoney") public Luckymoney create(@Valid Luckymoney luckymoney, BindingResult bindingResult) { // bindingResult返回验证的结果 if (bindingResult.hasErrors()) { System.out.println(bindingResult.getFieldError().getDefaultMessage()); return null; } luckymoney.setProducer(luckymoney.getProducer()); luckymoney.setMoney(luckymoney.getMoney()); return repository.save(luckymoney); }}