1、需要的jar包
2、springsevlet-config.xml配置
在spring3之后,任何支持JSR303的validator(如Hibernate Validator)都可以通过简单配置引入,只需要在配置xml中加入,这时validatemessage的属性文件默认为classpath下的ValidationMessages.properties:
<!-- support JSR303 annotation if JSR 303 validation present on classpath --> <mvc:annotation-driven />
如果不使用默认,可以使用下面配置:
<mvc:annotation-driven validator="validator" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!--不设置则默认为classpath下的ValidationMessages.properties --> <property name="validationMessageSource" ref="validatemessageSource"/> </bean><bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:validatemessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean>
3、hibernate validator constraint 注解
1 Bean Validation 中内置的 constraint 2 @Null 被注释的元素必须为 null 3 @NotNull 被注释的元素必须不为 null 4 @AssertTrue 被注释的元素必须为 true 5 @AssertFalse 被注释的元素必须为 false 6 @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 7 @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 8 @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 9 @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 10 @Size(max=, min=) 被注释的元素的大小必须在指定的范围内 11 @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内 12 @Past 被注释的元素必须是一个过去的日期 13 @Future 被注释的元素必须是一个将来的日期 14 @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式 15 16 Hibernate Validator 附加的 constraint 17 @NotBlank(message =) 验证字符串非null,且长度必须大于0 18 @Email 被注释的元素必须是电子邮箱地址 19 @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内 20 @NotEmpty 被注释的字符串的必须非空 21 @Range(min=,max=,message=) 被注释的元素必须在合适的范围内
Demo:
编写自己的验证类:
1 package com.journaldev.spring.form.validator; 2 3 import org.springframework.validation.Errors; 4 import org.springframework.validation.ValidationUtils; 5 import org.springframework.validation.Validator; 6 7 import com.journaldev.spring.form.model.Employee; 8 /** 9 *自定义一个验证类由于对员工信息进项验证(实现Validator接口) 10 */ 11 public class EmployeeFormValidator implements Validator { 12 13 //which objects can be validated by this validator 14 @Override 15 public boolean supports(Class<?> paramClass) { 16 return Employee.class.equals(paramClass); 17 } 18 //重写validate()方法编写验证规则 19 @Override 20 public void validate(Object obj, Errors errors) { 21 ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "id.required"); 22 23 Employee emp = (Employee) obj; 24 if(emp.getId() <=0){ 25 errors.rejectValue("id", "negativeValue", new Object[]{"‘id‘"}, "id can‘t be negative"); 26 } 27 28 ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required"); 29 ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "role.required"); 30 } 31 }
控制器代码:
1 package com.journaldev.spring.form.controllers; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.beans.factory.annotation.Qualifier; 10 import org.springframework.stereotype.Controller; 11 import org.springframework.ui.Model; 12 import org.springframework.validation.BindingResult; 13 import org.springframework.validation.Validator; 14 import org.springframework.validation.annotation.Validated; 15 import org.springframework.web.bind.WebDataBinder; 16 import org.springframework.web.bind.annotation.InitBinder; 17 import org.springframework.web.bind.annotation.ModelAttribute; 18 import org.springframework.web.bind.annotation.RequestMapping; 19 import org.springframework.web.bind.annotation.RequestMethod; 20 21 import com.journaldev.spring.form.model.Employee; 22 23 @Controller 24 public class EmployeeController { 25 26 private static final Logger logger = LoggerFactory 27 .getLogger(EmployeeController.class); 28 29 private Map<Integer, Employee> emps = null; 30 31 @Autowired 32 @Qualifier("employeeValidator") 33 private Validator validator; 34 35 @InitBinder 36 private void initBinder(WebDataBinder binder) { 37 binder.setValidator(validator); 38 } 39 40 public EmployeeController() { 41 emps = new HashMap<Integer, Employee>(); 42 } 43 44 @ModelAttribute("employee") 45 public Employee createEmployeeModel() { 46 // ModelAttribute value should be same as used in the empSave.jsp 47 return new Employee(); 48 } 49 50 @RequestMapping(value = "/emp/save", method = RequestMethod.GET) 51 public String saveEmployeePage(Model model) { 52 logger.info("Returning empSave.jsp page"); 53 return "empSave"; 54 } 55 56 @RequestMapping(value = "/emp/save.do", method = RequestMethod.POST) 57 public String saveEmployeeAction( 58 @ModelAttribute("employee") @Validated Employee employee, 59 BindingResult bindingResult, Model model) { 60 if (bindingResult.hasErrors()) { 61 logger.info("Returning empSave.jsp page"); 62 return "empSave"; 63 } 64 logger.info("Returning empSaveSuccess.jsp page"); 65 model.addAttribute("emp", employee); 66 emps.put(employee.getId(), employee); 67 return "empSaveSuccess"; 68 } 69 }
员工类代码:
1 package com.journaldev.spring.form.model; 2 3 public class Employee { 4 5 private int id; 6 private String name; 7 private String role; 8 9 public int getId() { 10 return id; 11 } 12 public void setId(int id) { 13 this.id = id; 14 } 15 public String getName() { 16 return name; 17 } 18 public void setName(String name) { 19 this.name = name; 20 } 21 public String getRole() { 22 return role; 23 } 24 public void setRole(String role) { 25 this.role = role; 26 } 27 28 }
jsp页面:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <%@ taglib uri="http://www.springframework.org/tags/form" 5 prefix="springForm"%> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>Employee Save Page</title> 10 <style> 11 .error { 12 color: #ff0000; 13 font-style: italic; 14 font-weight: bold; 15 } 16 </style> 17 </head> 18 <body> 19 20 <springForm:form method="POST" commandName="employee" 21 action="save.do"> 22 <table> 23 <tr> 24 <td>Employee ID:</td> 25 <td><springForm:input path="id" /></td> 26 <td><springForm:errors path="id" cssClass="error" /></td> 27 </tr> 28 <tr> 29 <td>Employee Name:</td> 30 <td><springForm:input path="name" /></td> 31 <td><springForm:errors path="name" cssClass="error" /></td> 32 </tr> 33 <tr> 34 <td>Employee Role:</td> 35 <td><springForm:select path="role"> 36 <springForm:option value="" label="Select Role" /> 37 <springForm:option value="ceo" label="CEO" /> 38 <springForm:option value="developer" label="Developer" /> 39 <springForm:option value="manager" label="Manager" /> 40 </springForm:select></td> 41 <td><springForm:errors path="role" cssClass="error" /></td> 42 </tr> 43 <tr> 44 <td colspan="3"><input type="submit" value="Save"></td> 45 </tr> 46 </table> 47 48 </springForm:form> 49 50 </body> 51 </html>
时间: 2024-10-25 02:33:44