1.创建 表单参数类/国际化文件
创建国际化资源文件ValidationMessages_en_US.properties
name=name\:
password=password\:
age=age\:
email=email\:
phone=phone\:
submit=submit
nullNameError=name not null
passwordLengthError=password length must between 6-10
ageMinError=age must 18
emailError=email format error
phoneError=phone must 150
创建国际化资源文件ValidationMessages_zh_CN.properties
name=\u59D3\u540D\uFF1A
password=\u5BC6\u7801\uFF1A
age=\u5E74\u9F84\uFF1A
email=\u90AE\u7BB1\uFF1A
phone=\u7535\u8BDD\uFF1A
submit=\u63D0\u4EA4
nullNameError=\u59D3\u540D\u4E0D\u80FD\u4E3A\u7A7A
passwordLengthError=\u5BC6\u7801\u957F\u5EA6\u5FC5\u987B 6-10 \u4E4B\u95F4
ageMinError=\u5E74\u9F84\u5FC5\u987B 18 \u4EE5\u4E0A
emailError=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E
phoneError=\u7535\u8BDD\u5FC5\u987B\u662F 150 \u5F00\u5934
用”{key}” 取得国际化value
package com.springmvc.hibernateValidator;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
public class User {
/*
* @Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
*
*
*
*
* message属性 验证失败提示的信息
*
*/
//非 "" 验证
@NotEmpty(message="{nullNameError}")
private String name;
/*
* 范围验证
* max 最大值
* min 最小值
*/
@Length(max=10,min=6,message="{passwordLengthError}")
private String password;
//最小值
@Min(value=18,message="{ageMinError}")
private int age;
//email 验证
@Email(message="{emailError}")
private String email;
//正则验证
@Pattern(regexp="^[150[0-9]+]{11}",message="{phoneError}")
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
2.创建 reg.jsp 和 suc.jsp
使用标签
<%@taglib prefix=”s” uri=”http://www.springframework.org/tags”%>
<%@taglib uri=”http://www.springframework.org/tags/form” prefix=”form”%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'reg.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form method="post" action="<%=path%>/validate.mvc">
<s:message code="name"></s:message>
<input type="text" name="name" value="${user.name}" />
<font color="red"><form:errors path="user.name"></form:errors>
</font>
<br />
<s:message code="password"></s:message>
<input type="password" name="password" value="${user.password }" />
<font color="red"><form:errors path="user.password"></form:errors>
</font>
<br />
<s:message code="age"></s:message>
<input type="text" name="age" value="${user.age }" />
<font color="red"><form:errors path="user.age"></form:errors>
</font>
<br />
<s:message code="email"></s:message>
<input type="text" name="email" value="${user.email}"/>
<font color="red"><form:errors path="user.email"></form:errors>
</font>
<br />
<s:message code="phone"></s:message>
<input type="text" name="phone" value="${user.phone }"/>
<font color="red"><form:errors path="user.phone"></form:errors>
</font>
<br />
<a href="<%=path %>/validate.mvc?locale=zh_CN">中文</a>
<a href="<%=path%>/validate.mvc?locale=en_US">English</a><br/>
<input type="submit" value="<s:message code="submit"></s:message>" />
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'reg.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
你的信息已经通过验证
<br />
姓名: ${user.name}
<br />
密码: ${user.password }
<br />
年龄: ${user.age }
<br />
邮箱:${user.email}
<br />
电话:${user.phone }
</body>
</html>
3.配置 web.xml
org.springframework.web.servlet.DispatcherServlet
org.springframework.web.context.ContextLoaderListener
<?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 和 springMvc 需要配置两 个 spring.xml 文件
mvc 配置 org.springframework.web.servlet.DispatcherServlet Servlet
跟servlet,mvc,文件上传等 有关的配置配置在这个<param-value>/WEB-INF/classes/dispatcherServlet.xml</param-value> 管理文件中
spring 配置 org.springframework.web.context.ContextLoaderListener Listener
框架整合 配置在<param-value>/WEB-INF/classes/ContextLoaderListener.xml</param-value> 这个配置文件中
sessionFactory
数据库连接池
事务管理
template 模板
组件扫描
datasource
事务切面
aop
-->
<!-- 配置charset-->
<filter>
<filter-name>characterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置 dispatcherServlet handler 管理 servlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/dispatcherServlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!-- 指定后缀名 -->
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
<!-- 配置模拟 提交 方式 -->
<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>
<!-- 配置log url 请求输出 到 console -->
<filter>
<filter-name>commonsRequestLoggingFilter</filter-name>
<filter-class>org.springframework.web.filter.CommonsRequestLoggingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>commonsRequestLoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置 ContextLoaderListener 加载spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/ContextLoaderListener.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
ContextLoaderListener.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:is = "http://www.w3.org/2001/XMLSchema-instance"
is:schemaLocation =
"
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
"
>
<!-- scan package beans -->
<context:component-scan base-package="com.springmvc.*">
</context:component-scan>
<!--
配置 国际化资源 资源文件
warn: id 必须是 messageSource
必须配置在contextLoaderListener.xml 监听器初始化文件中
-->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 注入绑定的资源文件名称 ValidationMessages
ValidationMessages_en.properties
ValidationMessages_zh_CN.properties
-->
<property name="basename" value="ValidationMessages"></property>
</bean>
</beans>
dispatcherServlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:is = "http://www.w3.org/2001/XMLSchema-instance"
is:schemaLocation =
"
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
"
>
<!-- scan package beans -->
<context:component-scan base-package="com.springmvc.*">
</context:component-scan>
<!-- 配置 springMvc 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置 多部件 -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!-- 可设置上传文件大小,上传类型,属性 等属性-->
</bean>
<!--自定义 验证工厂类 LocalValidatorFactoryBean 绑定验证使用的国际化bean-->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 引入 ContextLoaderListener.xml 中配置的 资源文件 bean -->
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
<!-- 启动,mvc注解扫描 指定验证类 验证器使用自定义验证器-->
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
<!-- 配置国际化locale解析器 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieMaxAge" value="100000"></property>
<property name="cookieName" value="clientLanguage"></property>
<property name="cookiePath" value="/"></property>
<property name="defaultLocale" value="zh_CN"></property>
</bean>
<!-- 配置 本地化:Spring MVC的本地化解析器
AcceptHeaderLocaleResolver:根据HTTP报文头的Accept-Language参数确定本地化类型,
如果没有显式定义本地化解析器,Spring MVC默认采用AcceptHeader- LocaleResolver。
CookieLocaleResolver:根据指定Cookie值确定本地化类型。
SessionLocaleResolver:根据Session中特定的属性值确定本地化类型。
LocaleChangeInterceptor:从请求参数中获取本次请求对应的本地化类型。
-->
<mvc:interceptors>
<bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
</bean>
</mvc:interceptors>
</beans>
4.创建 测试 handler
package com.springmvc.hibernateValidator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.util.logging.resources.logging;
@Controller("validate")
public class TestHandler {
private Logger rootLogger= Logger.getLogger(TestHandler.class);
@RequestMapping(value="/validate")
public String vald(
//必须 添加验证注解 在 表单对象上
@Valid
User user,
//BindingResult 验证是失败的字段的错误信息 放置在该实现类中
BindingResult br
){
if (br.hasErrors()) {
//获取验证失败数量
rootLogger.debug(br.getErrorCount());
List<ObjectError> errors = br.getAllErrors();
for(ObjectError error :errors){
rootLogger.debug(error);
}
//验证不通过跳回注册页面
return "/validate/reg.jsp";
}
//验证通过 跳转成功页面
return "/validate/suc.jsp";
}
}