利用Spring MVC 与 hibernate的JSR-303规范结合实现后台校验(简单案例):
JSR 303是Java EE 6中的一项子规范,叫做Bean Validation,官方参考实现是hibernate Validator,此实现与Hibernate ORM没有任何关系。JSR 303用于对Java Bean中的字段的值进行验证。
Spring-mvc.xml配置:
<!--JSR-303--> <mvc:annotation-driven validator="validator"/> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <property name="validationMessageSource" ref="messageSource"/> </bean> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="validatemessage"/> <property name="useCodeAsDefaultMessage" value="false"/> <property name="defaultEncoding" value="UTF-8"/> <property name="cacheSeconds" value="60"/> </bean> <bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="conversionService"> <bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean"></bean> </property> <property name="validator" ref="validator"/> </bean>
这里贴出部分代码,知道如何加注解即可:
import com.lemontree.common.utils.AjaxResult; import com.lemontree.common.utils.StringUtil; import com.lemontree.common.utils.email.EmailUtils; import org.hibernate.validator.constraints.NotEmpty; import java.util.Date; public class User { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user.id * * @mbg.generated Thu Mar 16 13:27:38 CST 2017 */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user.user_name * * @mbg.generated Thu Mar 16 13:27:38 CST 2017 */ @NotEmpty(message = "用户名不能为空") private String userName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user.password * * @mbg.generated Thu Mar 16 13:27:38 CST 2017 */ @NotEmpty(message = "密码不能为空") private String password; }
将@Validated 注解跟在实体类前面,BindingResult紧跟其后:
@RequestMapping(value = "/login.htm", method = RequestMethod.POST) public @ResponseBody AjaxResult login(@Validated User user, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) { if (bindingResult.hasErrors()){ List<FieldError> errorses = bindingResult.getFieldErrors(); if (CollectionUtils.isNotEmpty(errorses)){ errorses.forEach(item->{ System.out.println(item.getDefaultMessage()); }); } } }