spring3表单绑定验证

最近因项目不得不研究下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


以上是我的一些心得,估计也不是最好的方法,如果有更好,还恳请高手指导一下
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值