两者区别 @Valid @Validated 标准 标准JSR-303规范 增强JSR-303规范 包 javax.validation org.springframework.validation 验证结果 BindingResult result BindingResult result 分组支持 不支持 支持 分组序列 不支持 支持
两者区别
@Valid@Validated
分组示例
public interface First{} public interface Second{} public class User { // 所有都验证 @NotNull(message = "...") private int id; // First 才验证 @NotNull(message = "...", groups = { First.class }) private String username; // First 或 Second 才验证 @NotNull(message = "...", groups = { First.class, Second.class }) private String content; // First 验证 NotEmpty,Second 验证 Size @NotEmpty(message = "...", groups = { First.class }) @Size(message = "...", min = 3, max = 8, groups = { Second.class }) private String height; } // 只验证 Second 分组和没有分组的属性 public String save(@Validated( { Second.class }) User user, BindingResult result) { if (result.hasErrors()) { return "validate/error"; } return "redirect:/success"; }
分组序列
public interface GroupA {} public interface GroupB {} @GroupSequence( { GroupA.class, GroupB.class }) public interface Group {}
public @ResponseBody String save(@Validated({ Group.class }) User user, BindingResult result) { if(result.hasErrors()) { return false; } return true; }
嵌套验证
public class Item { @NotNull(message = "id不能为空") @Min(value = 1, message = "id必须为正整数") private Long id; @Valid @NotNull(message = "props不能为空") @Size(min = 1, message = "至少要有一个属性") private List<Prop> props; }
public class Prop { @NotNull(message = "pid不能为空") @Min(value = 1, message = "pid必须为正整数") private Long pid; @NotNull(message = "vid不能为空") @Min(value = 1, message = "vid必须为正整数") private Long vid; @NotBlank(message = "pidName不能为空") private String pidName; @NotBlank(message = "vidName不能为空") private String vidName; }
@RestController public class ItemController { @RequestMapping("/item/add") public void addItem(@Validated Item item, BindingResult bindingResult) { doSomething(); } }
验证多个对象
@Controller public class PeopleController { @RequestMapping("/add") public @ResponseBody String add(@Validated People pp, BindingResult result1, @Validated Person ps, BindingResult result2) { if(result1.hasErrors()) { return false; } if(result2.hasErrors()) { return false; } return true; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。