最近因项目不得不研究下spring表单验证,通过搜索资料,最后还是决定使用spring-modules-validation.jar
以下是相关的代码
实体bean
- public class Configuration{
- @NotNull
- @Length(min=3,max=10)
- private String name;//配置名称
- ...............
- }
controller
- @Autowired
- private Validator validator;
- @RequestMapping(CREATE)
- public String save (@ModelAttribute("configuration") Configuration object,BindingResult result, HttpServletRequest request,ModelMap model){
- //表单验证
- validator.validate(object, result);
- List<ObjectError> error = result.getAllErrors();
- log.debug("result>>"+result);
- if (result.hasErrors()) {
- model.addAttribute("objectErrorList",result.getAllErrors());
- return FORM;
- }
配置
- <bean id="configurationLoader" class="org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader"/>
- <bean id="validator" class="org.springmodules.validation.bean.BeanValidator" p:configurationLoader-ref="configurationLoader"/>
- <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" p:basename="classpath:errors">
- <property name="defaultEncoding" value="utf-8" />
- </bean>
- 后一个是设置一个errors.properties
jsp页面
- <c:forEach items="${objectErrorList}" var="error" varStatus="idx">
- ${idx.index+1 }:<spring:message code="${error.code}"/><br/>
- </c:forEach>
其实这里还有另外一种写法,就是不要使用errors.properties
而直接把异常的提示信息写在实体bean中
eg:
- @Length(min=3,max=10,message="xxxxx")
在这里的xxxxx如果是中文的话,记得需要先转码再复制填充进去
然后再jsp页面是需要这样调用
- <c:forEach items="${objectErrorList}" var="error" varStatus="idx">
- ${error.defaultMessage}<br/>
- </c:forEach>
另外
1.在实体bean中还可以设置其他的验证规则,这个可以研究下spring-modules-validation.jar中的org.springmodules.validation.bean.conf.loader.annotation.handler包下面的类,如@Email验证电子邮箱的输入
2.properties文件的中文问题可以这样解决,使用jdk中的native2ascii.exe工具
native2ascii.exe -encoding iso8859_1 errors.properties errors2.properties(其中的iso编码这个需要根据你系统的需要进行设置)
参考网址:
1.http://www.enavigo.com/2010/08/13/spring-bean-validation-error-code-list-for-custom-error-message/
2.http://wheelersoftware.com/articles/spring-bean-validation-framework-1.html
以上是我的一些心得,估计也不是最好的方法,如果有更好,还恳请高手指导一下