Spring_JSR 303标准的校验框架与SpringMVC际化、及校验字符串消息国际化

本文介绍如何在Spring MVC框架中实现数据校验,包括使用JSR 303标准和Spring内置的数据校验框架。文章详细展示了配置过程、常用的校验注解及其功能,并提供了一个完整的注册表单校验案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring 3.0拥有自己独立的数据校验框架,同时支持JSR 303标准的校验框架。SpringDataBinder在进行数据绑定时,可同时调用校验框架完成数据校验工作。在Spring MVC中,则可直接通过注解驱动的方式进行数据校验。

 

hibernate-validator-4.3.2.Final架包的下载地址:

https://sourceforge.net/projects/hibernate/?source=typ_redirect

 

架包支持:



校验框架的架包支持:

hibernate-validator-4.3.2.Final.jar

hibernate-validator-annotation-processor-4.3.2.Final.jar

jboss-logging-3.1.0.CR2.jar

validation-api-1.0.0.GA.jar

 

注    解

功能说明

@Null

 被注释的元素必须为 null

@NotNull

 被注释的元素必须不为 null

@NotEmpty

 被注释的元素必须不为 null   不为空字符串””

@AssertTrue

 被注释的元素必须为 true

@AssertFalse

 被注释的元素必须为 false

@Min(value)

 被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@Max(value)

 被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@DecimalMin(value)

 被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@DecimalMax(value)

 被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@Size(max, min)

 被注释的元素的大小必须在指定的范围内

@Digits (integer, fraction)

 被注释的元素必须是一个数字,其值必须在可接受的范围内

@Past

 被注释的元素必须是一个过去的日期

@Future

 被注释的元素必须是一个将来的日期

@Pattern(regexp)

  被注释的元素必须是符合正则表达式


 web.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- 加载spring.xml配置文件 -->
	<!-- spring 要使用springmvc的标签和国际化必须加载spring-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring.xml</param-value>
	</context-param>
	<!-- 配置spring过滤器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- springmvc -->
	<filter>
		<filter-name>utf</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>utf</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 <filter>
  	<filter-name>myencode</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>

 <!-- servlet一般是不支持delete和put  所以要配置一个过滤器 -->
 <filter>
 	<filter-name>hidden</filter-name>
 	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
 </filter>
 <filter-mapping>
 	<filter-name>hidden</filter-name>
 	<url-pattern>/*</url-pattern>
 </filter-mapping>

  <servlet>
  	<servlet-name>spring</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class>
    <init-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>/WEB-INF/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
  	<servlet-name>spring</servlet-name>
  	<url-pattern>*.action</url-pattern>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>



springmvc.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		
		"
	>
	
	
	<!-- 扫描spring注解 -->
	<context:component-scan base-package="cn.et"></context:component-scan>
	
	<!-- 实体类注解的国际化 -->
	<bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
		<property name="validationMessageSource" ref="messageSource"></property>
	</bean>
	
	<bean id="" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" ></bean>
	
	<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
	
	<!-- 验证消息必须配置这个,不让验证消息不生效 <mvc:annotation-driven></mvc:annotation-driven>-->
	
	<mvc:annotation-driven validator="myValidator">
	</mvc:annotation-driven>
	
	<!-- 默认获取到了request_locale的值会调用AcceptHeaderLocaleResolver 存储  这个方法的setLocale不能用
		需要用SessionLocaleResolver来替代默认  将request_locale的值存放在session中
	-->
	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
	
	<mvc:interceptors>
		<!-- 定义i18n拦截器  用于获取请求对中的local对象  zh_CN -->
		<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
		<property name="paramName" value="request_locale"></property>
		</bean>
	</mvc:interceptors>
</beans>



spring.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		"
	>
	<!-- 一定要放在spring.xml配置文件中 -->	
	<!-- id的名字就是类最后面二个单词  以小写字母开头 -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="/my"></property>
	</bean>
	
</beans>



my_en_US.properties:

 

userName=userName
password=password
myIntroduce=myIntroduce
hobby=hobby
sex=sex
interest=interest
addr=addr

running=running
swimming=swimming

man=man
woman=woman

movie=movie
travel=travel

ShenZhenCity=ShenZhenCity
LongHuaNewDistrict=LongHuaNewDistrict
NanShanDistrict=NanShanDistrict

GuangZhouCity=GuangZhouCity
TianHeDistrict=TianHeDistrict
BaiYunDistrict=BaiYunDistrict

YongZhouCity=YongZhouCity
LengShuiTanDistrict=LengShuiTanDistrict
LingLingDistrict=LingLingDistrict

submit=submit
rePasswordError=password and repassword must be simil
userError=user is not null



my_zh_CN.properties:

userName=\u7528\u6237\u540D
password=\u5BC6\u7801
myIntroduce=\u81EA\u6211\u4ECB\u7ECD
hobby=\u7231\u597D
sex=\u6027\u522B
interest=\u5174\u8DA3
addr=\u5730\u5740

running=\u8DD1\u6B65
swimming=\u6E38\u6CF3

man=\u7537
woman=\u5973

movie=\u770B\u7535\u5F71
travel=\u65C5\u6E38

ShenZhenCity=\u6DF1\u5733\u5E02
LongHuaNewDistrict=\u9F99\u534E\u65B0\u533A
NanShanDistrict=\u5357\u5C71\u533A

GuangZhouCity=\u5E7F\u5DDE\u5E02
TianHeDistrict=\u5929\u6CB3\u533A
BaiYunDistrict=\u767D\u4E91\u533A

YongZhouCity=\u6C38\u5DDE\u5E02
LengShuiTanDistrict=\u51B7\u6C34\u6EE9\u533A
LingLingDistrict=\u96F6\u9675\u533A

Chinese=\u4E2D\u6587
English=\u82F1\u6587

submit=\u63D0\u4EA4
rePasswordError=\u5BC6\u7801\u4E0D\u4E00\u81F4
userError=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A




jsp入口:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="s"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="st"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
	<script type="text/javascript">
		
		function $(name){
			return document.getElementsByName(name);
		}
		
		function checkForm(){
			
			var userName=$("userName")[0].value;
			
			/* if(userName == null || userName == ""){
				alert("用户名不能为空!");
				return;
			} */
			
			document.forms[0].submit();		
		}
	</script>
</head>
<body>
	<a href="${pageContext.request.contextPath}/homeValidator.action?request_locale=en_US"><st:message code="English"></st:message></a><br/>
	<a href="${pageContext.request.contextPath}/homeValidator.action?request_locale=zh_CN"><st:message code="Chinese"></st:message></a><br/>

	<h4><st:message code="register"></st:message></h4>
	<form action="${pageContext.request.contextPath}/homeValidator.action">
		<table>
			<tr>
				<td><st:message code="userName"></st:message></td>
				<td><input type="text" name="userName" /></td>
				<td><s:errors path="user.userName"></s:errors></td>
			</tr>
			<tr>
				<td><st:message code="password"></st:message></td>
				<td><input type="text" name="password" /></td>
				<td><s:errors path="user.password"></s:errors></td>
			</tr>
			<tr>
				<td><st:message code="repassword"></st:message></td>
				<td><input type="text" name="repassword" /></td>
				<td><s:errors path="user.repassword"></s:errors></td>
			</tr>
			<tr>
				<td><st:message code="sex"></st:message></td>
				<td><input type="radio" name="sex" value='1'/><st:message code="man"></st:message>
					 <input type="radio" name="sex" value='0'/><st:message code="woman"></st:message>
				</td>
				<td><s:errors path="user.sex"></s:errors></td>
			</tr>
			<tr>
				<td><st:message code="birthday"></st:message></td>
				<td><input type="text" name="birthday" /></td>
				<td><s:errors path="user.birthday"></s:errors></td>
			</tr>
			<tr>
				<td><st:message code="location"></st:message></td>
				<td><input type="text" name="location" /></td>
				<td><s:errors path="user.location"></s:errors></td>
			</tr>
			<tr>
				<td><st:message code="phone"></st:message></td>
				<td><input type="text" name="phone" /></td>
				<td><s:errors path="user.phone"></s:errors></td>
			</tr>
			<tr>
				<td><st:message code="email"></st:message></td>
				<td><input type="text" name="email" /></td>
				<td><s:errors path="user.email"></s:errors></td>
			</tr>
			<tr align="center">
				<td colspan="2"><font color="gray" size="2">
					<st:message code="remark1"></st:message>   <br/>
					<st:message code="remark2"></st:message> <a href="javascript:;" ><st:message code="click"></st:message></a>
				</font></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
				<button onclick="checkForm()" ><st:message code="registerNow"></st:message></button>
				</td>
			</tr>
		</table>
		
	</form>
</body>
</html>



Entity类:

package cn.et.springmvc.homework03;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

/**
 * 验证有二种
 * 	1.声明式验证(本类用的是这个)
 * 	2.编程式验证
 * @author Administrator
 *
 */
public class UserInfo {

	private String userId;
	//不能为null和不能为空字符串""
	//{userError} 国际化
	@NotEmpty(message="{userNotEmpty}")
	private String userName;
	@Pattern(regexp="[0-9]{6}",message="{passwordError}")
	private String password;
	//需要在Action类里进行编程式验证
	private String repassword;
	@NotNull(message="{sexError}")
	private String sex;
	@Pattern(regexp="\\d{4}-\\d{1,2}-\\d{2}",message="{birthdayError}")
	private String birthday;
	@NotEmpty(message="{locationError}")
	private String location;
	@Pattern(regexp="[0-9]{11}",message="{phoneError}")
	private String phone;
	@NotEmpty(message="{emailNotEmpty}")
	@Email(message="{emailError}")
	private String email;
	
	
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
}



Action类:

package cn.et.springmvc.homework03;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class ValidatorAction {
	
	
	
	//自动装配
	@Autowired
	private MessageSource source;
	

	/**
	 * 验证消息同时处理多个对象BindingResult跟在对象后面即可。
	 * Errors是BindingResult的父接口,效果一样,只是不能new FieldError();
	 * @param user
	 * @param result
	 * @param locale
	 * @return
	 */
	@RequestMapping(value="/homeValidator")
	public String validator(@ModelAttribute("user")@Valid UserInfo user,BindingResult result, Locale locale){
		/**
		 * 编程式验证
		 * 判断二次输入的密码是否一致
		 */
		if(user.getPassword() != null && !user.getPassword().equals(user.getRepassword())){
			//国际化
			String errorMsg = source.getMessage("inconsistency", null, locale);
			result.addError(new FieldError("user", "rePassword", errorMsg));
		}
		
		//判断是否验证失败
		if(result.hasErrors()){
			return "/homework03/form.jsp";
		}
		return "/homework03/form.jsp";
	}
	
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值