1、在http://www.cnblogs.com/wtzl/p/8830678.html编程式校验基础上
2.新增jar包三个
3.StudentModel.java(声明式)
package 声明式校验; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range; public class StudentModel {
@NotNull(message="name不能为空")
@Length(min=6,max=10,message="长度是6~10个字符")
private String name;
@Range(min=10,max=40,message="age在10~40之间")
private int age;
@Email(message="邮箱地址不正确")
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
} }
4.ValidationAnnotationController .java(控制器简化)
package 声明式校验; import javax.validation.Valid; import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class ValidationAnnotationController {
@RequestMapping("stu.html")
public String validStudent(@Valid StudentModel student,Errors errors){
if(errors.hasErrors()){
return "error2";
}
return "result";
}
}
5.springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 注解扫描 -->
<context:component-scan base-package="com.wt.entity"/> <context:component-scan base-package="声明式校验"/>
<mvc:annotation-driven></mvc:annotation-driven> <!-- 完成视图的对应 -->
<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/jsp/example1/"/>
<property name="suffix" value=".jsp"/>
</bean> </beans>
6.jsp文件一样
7.测试效果