🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 引入JSR303框架** ```xml <!-- JSR 303 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.1.Final</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.1.0.CR2</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> ``` **2. 在实体类的属性上标注JSR 303约束注解** ```java @Data public class Supplier { @NotEmpty(message = "code不能为空!") private String code; @NotEmpty(message = "phone不能为空!") @Length(min = 7, max = 11, message = "phone的长度应该在7~11位之间!") private String phone; @DateTimeFormat(pattern = "yyyy-MM-dd") @Past(message = "modifiedTime必须是一个过去的时间") private Date modifiedTime; } ``` **3. controller层** ```java @Controller @RequestMapping("/supplier") public class SupplierController { @GetMapping("/to/page") public String toSupplier(@ModelAttribute("supplier") Supplier supplier) { return "supplier"; } /** * 使用注解@Valid来验证数据是否符合要求,@Valid标记的参数后面必须紧接着BindingResult,否则Spring抛出异常 */ @PostMapping("/action/add") public String addSupplier(@Valid Supplier supplier, BindingResult bindingResult, HttpServletRequest request) { if (bindingResult.hasErrors()) { System.out.println("数据绑定异常!"); request.setAttribute("data", "数据绑定异常"); return "supplier"; } request.setAttribute("data", supplier.toString()); return "supplier"; } } ``` **4. 视图层** *`webapp/WEB-INF/views/supplier.jsp`* ```html <body> <h1>${ data }</h1> <fieldset> <legend>添加供应商</legend> <fm:form method="post" modelAttribute="supplier" action="${pageContext.request.contextPath }/supplier/action/add"> <div> code:<fm:input path="code"/>*<fm:errors path="code" style="color:red"/> </div> <div> phone:<fm:input path="phone"/>*<fm:errors path="phone" style="color:red"/> </div> modifiedTime:<fm:input path="modifiedTime"/>*<fm:errors path="modifiedTime" style="color:red"/> <div> <input type="submit" value="提交"/> </div> </fm:form> </fieldset> </body> ``` **5. 测试** (2)验证不通过。 ![](https://img.kancloud.cn/43/ff/43ff369226552bc6bf6fb04212e9689f_1681x331.jpg) (3)验证通过。 ![](https://img.kancloud.cn/46/c7/46c7cad303518a9b79afb5e94a00a69c_2300x355.jpg)