Spring mvc 数据验证框架注解

来源:互联网 发布:乐视电视mac码多少位 编辑:程序博客网 时间:2024/06/05 17:31

要使用该注解必须导入一些架包,架包下载地址:http://hibernate.org/orm/



要使用驱动注解的效验如以下:

package com.et.SpringMvc.TL.lesson03.hw;import java.util.Locale;import javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.MessageSource;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class LoginUserAcion {@Autowiredprivate MessageSource messageSource;@RequestMapping(value="/register")public String loginUser(/*该注解就是驱动效验注解*/@Valid LoginUserEntity lue,/*错误消息存储的地方*/BindingResult br,/*将错误消息国际化的时候用到*/Locale l){/* * 编程式验证,判断密码是否一致 * */ if(!(lue.getPassword().equals(lue.getTwicePassword()))){/* * 获取到错误消息(getMessage("twoPassword", null, l)) *      资源文件中的“键”   null  语言对象 * */String message = messageSource.getMessage("twoPassword", null, l);/* * 添加错误消息 * */br.addError(new FieldError("loginUserEntity", "twicePassword", message));} /*  * 发生错误跳转的界面  * */if(br.hasErrors()){return "/lesson03/XXXregister.jsp";}/* * 成功跳转的界面 * */return "/lesson03/success.jsp";}}

在spring配置文件中引用国际化资源文件:

<!--     引用国际化的资源文件,id必须是  messageSource     -->    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">    <!--     注入国际化的资源文件     -->    <property name="basename" value="/com/et/SpringMvc/TL/lesson03/hw/XXXregister"></property>    </bean>

在springMvc中引用国际化:

<!--     引用国际化     -->    <bean id="factoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">    <!--     注入spring配置文件中的messageSource     -->    <property name="validationMessageSource" ref="messageSource"></property>    </bean>    <!--     注入到自定义消息转换器中     -->    <mvc:annotation-driven validator="factoryBean">    </mvc:annotation-driven>

在使用上面之前需要在web.xml文件中将spring配置文件加载进来:

<context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:/spring.xml</param-value>  </context-param>  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>


效验框架常用的注解地址:

http://www.cnblogs.com/MarsJiang/p/springMVC_annotations.html

原创粉丝点击