1.首先經過Maven導入JSR303架包。前端
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.7.Final</version> </dependency>
2.而後修改Bean對象的定義,添加校驗註解java
@Pattern(regexp="(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,6})",message="error") private String empName; private String gender; @Pattern(regexp="^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$",message="error") private String email;
3.而後在控制器中使用這個校驗規則後端
@RequestMapping(value="/emp",method=RequestMethod.POST) @ResponseBody public String saveEmp(@Valid Employee employee,BindingResult result){ if(result.hasErrors()){ return "error"; }else { employeeService.add(employee); return "success"; } }
常見的註解開發中將對象封裝後,添加@Valid註解 設置出現不符合校驗規則的返回值app
4.而後前端獲取後端校驗結果 根據結果設置不一樣的提示信息。hibernate