springMVC可以通过多种验证框架的集成:
例如Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证。后面的例子使用了3个jar包:
hibernate-validator-4.3.1.Final.jar
jboss-logging-3.3.0.Final.jar
validation-api-1.1.0.Final.jar
下面是一个简单的验证例子,首先是 springnvc 配置文件:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 扫描注解的驱动 -->
<mvc:annotation-driven validator="validator" />
<!-- 设置扫描包 -->
<context:component-scan base-package="com.springmvc.controllers" />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
<!-- 不配置则默认为classPath下的ValidationMessages -->
<property name="validationMessageSource" ref="validationMessageSource"></property>
</bean>
<bean id="validationMessageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:validatorMessages"/> <!-- 资源路径 -->
<property name="fileEncodings" value="utf-8" />
<property name="cacheSeconds" value="1200" /> <!-- 缓存时间 -->
</bean>
<!-- 视图解析器 -->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
然后是验证资源:
validatorMessages
.properties
文件:
input.user.age=\u5E74\u9F84\u4E0D\u80FD\u4E3A\u7A7A
input.user.ager=\u5E74\u9F84\u5FC5\u987B\u57281~99\u4E4B\u95F4
控制器的代码:
package com.springmvc.controllers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.pojo.User;
@Controller
@RequestMapping("/validator/")
public class ValidatorController {
@RequestMapping("index")
public ModelAndView index(HttpServletRequest request,HttpServletResponse response) {
System.out.println("**********ValidatorController——index***********");
return new ModelAndView("validator");
}
//使用注解@Valid对参数user进行验证
@RequestMapping("validator")
public String validator(@Valid @ModelAttribute("user") User user,BindingResult result) throws Exception {
if(result.hasErrors()) { //判断是否有验证错误
return "validator"; //返回表单提交页面
}
return "simple"; //验证均通过后,跳转的页面
}
}
实体类
U
ser:
package com.springmvc.pojo;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
public class User {
@NotEmpty(message = "name is null !")
private String name;
@NotNull(message="{input.user.age}") //validatorMessages中的input.user.age=年龄不能为空
@Range(min=1,max=99,message="{input.user.ager}")//年龄必须在1~99之间
private Integer age;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
}
}
在工程的欢迎页面写一个转发:
<%response.sendRedirect("validator/index");%>
访问控制器里的index( )方法,跳转到/WEB-INF/jsp/目录下的validator.jsp的表单提交页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form action="validator" method="post" modelAttribute="user">
<div>
name:<input name="name" /><form:errors path="name"></form:errors>
</div>
<div>
age:<input name="age" /><form:errors path="age"></form:errors>
</div>
<div>
birthday:<input name="birthday" />
</div>
<div><input type="submit" value="提交"></div>
</form:form>
</body>
</html>
运行工程,到表单提交页面,如下图:
点击提交:
当年龄超出限制:
点击提交: