无需消息属性文件与资源包的Spring MVC Validator实现咨询
我来给你详细说说怎么实现不依赖消息属性文件和资源包的Spring MVC Validator验证,完全不用配置那些.properties文件,直接在代码里搞定:
1. 创建自定义Validator类
首先写一个自定义验证器,实现Spring的Validator接口,在验证逻辑里直接硬编码错误消息(跳过资源包读取)。针对你的keyUserRegistration模型类,示例代码如下:
import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class UserRegistrationValidator implements Validator { @Override public boolean supports(Class<?> clazz) { // 指定该验证器支持的模型类 return KeyUserRegistration.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { KeyUserRegistration user = (KeyUserRegistration) target; // 验证userId:不能为空且长度≥3位 ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", null, "用户ID不能为空"); if (user.getUserId() != null && user.getUserId().length() < 3) { errors.rejectValue("userId", null, "用户ID长度不能少于3位"); } // 验证userName:不能为空 ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", null, "用户名不能为空"); // 验证emailId:格式合法性校验 if (user.getEmailId() != null && !user.getEmailId().matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")) { errors.rejectValue("emailId", null, "邮箱格式不正确"); } // 验证password:不能为空且长度≥6位 ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", null, "密码不能为空"); if (user.getPassword() != null && user.getPassword().length() < 6) { errors.rejectValue("password", null, "密码长度不能少于6位"); } // dob、lastName等其他字段的验证逻辑可以按需添加 } }
这里要注意:rejectIfEmptyOrWhitespace和rejectValue的第三个参数传null(不用指定消息码),第四个参数直接写错误消息文本,彻底摆脱对消息属性文件的依赖。
2. 在Controller中绑定Validator
在你的Controller里,用@InitBinder注解注册这个自定义验证器,让Spring MVC处理请求时自动调用它验证模型:
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.WebDataBinder; @Controller public class UserRegistrationController { @InitBinder("keyUserRegistration") protected void initBinder(WebDataBinder binder) { // 添加自定义验证器到绑定器 binder.addValidators(new UserRegistrationValidator()); } @PostMapping("/checkRegistration.do") public String processRegistration(@Valid KeyUserRegistration user, BindingResult result, Model model) { // 如果验证出错,返回表单页面重新填写 if (result.hasErrors()) { return "registrationForm"; // 替换成你的JSP页面名称 } // 验证通过,执行后续业务逻辑(比如保存用户) return "successPage"; } }
@Valid注解会触发验证流程,BindingResult会收集所有验证错误,你可以根据它的状态决定返回表单还是进入后续流程。
3. JSP页面显示错误
你的JSP里已经有<form:errors>标签了,直接保留即可,它会自动读取我们在Validator中设置的错误消息:
<form:form method="POST" modelAttribute="keyUserRegistration" action="checkRegistration.do"> <table width="100%" border="0"> <tr> <td> <div class="form-control"> <form:errors path="userId" cssClass="error-text"/> <label> <p> User ID<small class="required">*</small> </p> <form:input path="userId" id="userId"/> </label> </div> </td> </tr> <!-- userName字段示例 --> <tr> <td> <div class="form-control"> <form:errors path="userName" cssClass="error-text"/> <label> <p> User Name<small class="required">*</small> </p> <form:input path="userName" id="userName"/> </label> </div> </td> </tr> <!-- emailId、password等字段按照相同逻辑添加 --> </table> <button type="submit">完成注册</button> </form:form>
当验证不通过时,对应的<form:errors>标签会直接输出我们在Validator里写的错误文本,全程不需要任何消息属性文件或资源包。
原理说明
Spring的Validator接口允许直接传入错误消息文本,而非依赖消息码去资源文件中查找。当我们在rejectValue或rejectIfEmptyOrWhitespace中传入第四个参数时,Spring会直接将该文本存入BindingResult,页面上的<form:errors>标签就能直接读取并展示。
内容的提问来源于stack exchange,提问作者kavya

