Hibernate Validator (从配置到国际化)

最近在改一个SSM项目,需要用到框架的校验,之前没有用过,从实现校验到检验提示的国际化,也是废了一番功夫,话不多说教程发上!

第一步,下载Hibernate-validator包,可百度进入官方下载页面,我下载的是6.0.9



第二步,将改压缩包中的相关JAR包导入到你的工程中去(此处留意一下工程中有没有重复JAR包)

第三步,在你的项目中配置 Validator(此处贴出相关配置文件)

springmvc-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!-- 配置包扫描器,扫描@Controller注解的类 -->
	<context:component-scan base-package="example.controller" />
	<!-- 加载注解驱动 -->
	<mvc:annotation-driven />
	<!-- 配置视图解析器 -->
	<bean class=
    "org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

applicationcontext.xml

 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    	<property name="basename">
    		<value>resource</value>
    	</property>
    </bean>
   <!--  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    	<property name="cookieMaxAge" value="604800"></property>
    	<property name="defaultLocale" value="en_US" ></property>
    	<property name="cookieName" value="resource"></property>
    </bean> -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    	<property name="defaultLocale" value="en_US" ></property>
    </bean>
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">    
      <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>    
      <!-- 这里配置将使用上面国际化配置的messageSource -->  
      <property name="validationMessageSource" ref="messageSource"/>    
  </bean>  

第四步,实现检验

1.在你要检验的类加上注解

Teach.java

//此类定义为POJO
public class Teach {
	/*private long id;
	// 
	private String name;
	// 
	private String banben;
	// 
	private String author;
	// 
	private String neirong;
	
	private String pdf_dir;*/
	private long outlineId;
	@Length(min=2,message="{outlineName}")
	private String outlineName;
	@NotEmpty(message="{Edition}")//message="{Validator_outlineEdition}"不写可调用默认
	private String outlineEdition;
	@Length(min=2,max=15,message="{Author}")//message="{Validator_outlineAuthor}"
	private String outlineAuthor;
	private String outlineDetail;
	private String outlinePdf_dir;

	public String getOutlinePdf_dir() {
		return outlinePdf_dir;
	}

	public void setOutlinePdf_dir(String pdf_dir) {
		this.outlinePdf_dir=pdf_dir;
	}

	public long getOutlineId() {
		return outlineId;
	}

	public void setId(long id) {
		this.outlineId = id;
	}
	public String getOutlineName() {
		return outlineName;
	}

	public void setOutlineName(String name) {
		this.outlineName = name;
	}
	public String getOutlineEdition() {
		return outlineEdition;
	}

	public void setOutlineEdition(String banben ) {
		this.outlineEdition =banben;
	}
	public String getOutlineAuthor() {
		return outlineAuthor;
	}

	public void setOutlineAuthor(String author) {
		this.outlineAuthor = author;
	}
	public String getOutlineDetail() {
		return outlineDetail;
	}

	public void setOutlineDetail(String neirong) {
		this.outlineDetail = neirong;
	}
	public String toString() {
		return this.getOutlineId()+this.getOutlineName()+this.getOutlineAuthor()+this.getOutlineEdition()+this.getOutlineDetail();
	}

}

代码中message="{...}"的形式是为了完成国际化(第五步说明如何进行国际化校验),如不需要“”可填任意字符串。

此处给出常用的注解

    注解                                      作用

@Valid 被注释的元素是一个对象,需要检查此对象的所有字段值
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式


Hibernate Validator 附加的 constraint

注解 作用
@Email 被注释的元素必须是电子邮箱地址
@Length(min=, max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=, max=) 被注释的元素必须在合适的范围内
@NotBlank 被注释的字符串的必须非空
@URL(protocol=,
host=,    port=, 
regexp=, flags=)
被注释的字符串必须是一个有效的url
@CreditCardNumber
被注释的字符串必须通过Luhn校验算法,
银行卡,信用卡等号码一般都用Luhn
计算合法性
@ScriptAssert
(lang=, script=, alias=)
要有Java Scripting API 即JSR 223 
("Scripting for the JavaTM Platform")的实现
@SafeHtml
(whitelistType=, 
additionalTags=)
classpath中要有jsoup包

hibernate补充的注解中,最后3个不常用,可忽略。

主要区分下@NotNull  @NotEmpty  @NotBlank 3个注解的区别:

@NotNull           任何对象的value不能为null

@NotEmpty       集合对象的元素不为0,即集合不为空,也可以用于字符串不为null

@NotBlank        只能用于字符串不为null,并且字符串trim()以后length要大于0

2.控制器例子

@RequestMapping("/addMessage")
	public String addMessage(@Valid @ModelAttribute("teach")Teach teach,BindingResult Br,HttpServletRequest request,HttpServletResponse response) {
		try {
			if(Br.hasErrors()) {

				return "index";
			}
			
			teachService.addMessage(teach);	

	}catch(Exception e) {
		e.printStackTrace();}
		return "index";
	}
@valid 和BindingResult必须连写此处注意!

3.前端

<form:form modelAttribute="teach" action="${pageContext.request.contextPath }/addMessage" method="post">
<tr>
			<td align="right"><spring:message code="Edition"></spring:message></td>
			<td><input type="text" name="outlineEdition"></td>
			<td nowrap="nowrap"><form:errors path="outlineEdition" cssStyle="color:red"/></td>
		</tr>

		<tr>
			<td align="right"><spring:message code="Author"></spring:message></td>
			<td><input type="text" name="outlineAuthor" /></td>
			<td nowrap="nowrap"><form:errors path="outlineAuthor" cssStyle="color:red"/></td>
		</tr>

</form:form>

为了简单,我贴出了其中两个的检验的,<form:form>标签需要导入

<%@ taglib prefix="form"   uri="http://www.springframework.org/tags/form" %>
4.效果图

 
 

第五步,校验提示信息的国际化

1.将下载好的Hibernate validator包中的Hibernate-validator-xxxx.Final.jar包解压缩


2.在解压缩文件夹中找到其中的org/hibernate/validator中找到你要的.properties文件

这里我以英文和中文为例,将如下两个文件拷贝到项目的src中去,自己在其中建立一个名字相同的文件也可以


然后加入自己自定义的键值对,调用的时候就message="{key}"的形式,参照上文,和国际化操作没有什么区别了。

中文


英文


3.效果图


原创内容,需要整个工程的可以留言,转载请注明出处!

猜你喜欢

转载自blog.csdn.net/qq_37922457/article/details/80256182