Spring @Valid和@Validated區別和用法例項
阿新 • • 發佈:2020-04-27
兩者區別
@Valid |
@Validated | |
---|---|---|
標準 | 標準JSR-303規範 | 增強JSR-303規範 |
包 | javax.validation | org.springframework.validation |
驗證結果 | BindingResult result | BindingResult result |
分組支援 | 不支援 | 支援 |
分組序列 | 不支援 | 支援 |
型別註解 | ? | 支援 |
方法註解 | 支援 | 支援 |
方法引數註解 | 支援 | 支援 |
建構函式註解 | 支援 | ? |
成員屬性註解 | 支援 | 不支援 |
巢狀驗證 | 支援 | 不支援 |
分組示例
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; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。