web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:spring-validate.xml</param-value>
</context-param>
<!-- POST中文乱码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-mvc.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<!-- 若想使用验证框架,必须使用自动注册ioc机制 -->
<context:component-scan base-package="com.lyf.controller" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
spring-validate.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- validationMessageSource属性:指定国际化错误消息从哪里取,
此处使用之前定义的messageSource来获取国际化消息
;如果此处不指定该属性,
则默认到classpath下的ValidationMessages.properties取国际化错误消息。 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 以发布到服务器的路径为准-->
<property name="basename" value="classpath:messages" />
<property name="fileEncodings" value="utf-8" />
<property name="cacheSeconds" value="120" />
</bean>
</beans>
spring.xml
s<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:default-servlet-handler/><!-- 只针对静态页,jsp可不用 -->
</beans>
messages.properties
NotEmpty.userModel.userName=用户名不能为空.
NotNull.userModel.age=年龄不能为空
NotEmpty.userModel.password=密码不能为空
NotEmpty.userModel.xm=真实姓名不能为空
Pattern.userModel.age=必须数字
Range.userModel.age=超范围了
UserModel
package com.lyf.po;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.Pattern;
/**
* Created by fangjiejie on 2017/6/6.
*/
public class UserModel {
@NotEmpty
private String username;
@NotEmpty
private String password;
@NotEmpty
@Pattern(regexp = "^\\d+$")
@Range(min=0,max = 99)
private String age;
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 getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
ValidateController
package com.lyf.controller;
import com.lyf.po.UserModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
import java.util.Map;
/**
* Created by fangjiejie on 2017/6/6.
*/
@Controller
@RequestMapping("/validate")
public class ValidateController {
//1.spring-mvc配置必须使用自动注解形式,否则不好使
//2.视图层必须使用spring控件,否则不好使
//3.以下语句必须首先实例化个空对象,并且装在model中,否则出现找不到属性错误
//键的名字是"userModel",且值是vo的类名,首字母小写,契约式编程
//4.视图层中必须有commandName:"userModel",且值是vo的类名,首字母小写,契约式编程
@RequestMapping("/show")
public String showForm(Map map){
UserModel user=new UserModel();
map.put("user",user);
return "validationform";
}
@RequestMapping("/val")
public String validate(@Valid @ModelAttribute("user") UserModel user, BindingResult result, Model model){
if(result.hasErrors()){
return "validationform";
}else{
return "validationsuccess";
}
}
}
index.jsp
<%--
Created by IntelliJ IDEA.
User: fangjiejie
Date: 2017/6/6
Time: 16:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/validate/show">表单验证</a>
</body>
</html>
validationform.jsp
<%--
Created by IntelliJ IDEA.
User: fangjiejie
Date: 2017/6/6
Time: 16:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title</title>
</head>
<body>
<!-- 必须使用Spring的组件 -->
<form:form method="post" action="/validate/val" commandName="user">
<h4 align="center"><u>登录页</u></h4>
<table align="center">
<tr>
<td>用户名:</td>
<td><form:input path="username" /><font color="red">
<form:errors path="username" /></font></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="number" name="age" value="10" ><font color="red">
<form:errors path="age" /></font></td>
</tr>
<tr>
<td>密码:</td>
<td><form:password path="password" /><font color="red">
<form:errors path="password" /></font>
</td>
</tr>
<tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
validationsuccess.jsp
<%--
Created by IntelliJ IDEA.
User: fangjiejie
Date: 2017/6/6
Time: 16:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>注册成功!</h2>
</body>
</html>