1、index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/test/register.do" method="get">
姓名:<input type="text" name="name"/>${nameErrorMSG }<br>
成绩:<input type="text" name="score"/>${scoreErrorMSG }<br>
电话:<input type="text" name="tel"/>${telErrorMSG }<br>
<input type="submit" value="注册"/><br>
</form>
</body>
</html>
2、Class Student
package com.beans;
import java.io.Serializable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class Student implements Serializable {
@NotEmpty(message = "姓名不能为空!")
@Size(min = 0, max = 20, message = "姓名长度必须在{min}-{max}字符之间!")
private String name;
@Min(value = 0, message = "成绩不能小于{value}!")
@Max(value = 100, message = "成绩不能大于{value}!")
private double score;
@NotEmpty(message = "手机号不能为空!")
@Pattern(regexp = "^1[34578]\\d{9}$", message = "手机号码格式不正确!")
private String tel;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, double score, String tel) {
super();
this.name = name;
this.score = score;
this.tel = tel;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the score
*/
public double getScore() {
return score;
}
/**
* @param score the score to set
*/
public void setScore(double score) {
this.score = score;
}
/**
* @return the tel
*/
public String getTel() {
return tel;
}
/**
* @param tel the tel to set
*/
public void setTel(String tel) {
this.tel = tel;
}
@Override
public String toString() {
return "Student [name=" + name + ", score=" + score + ", tel=" + tel + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((tel == null) ? 0 : tel.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(score) != Double.doubleToLongBits(other.score))
return false;
if (tel == null) {
if (other.tel != null)
return false;
} else if (!tel.equals(other.tel))
return false;
return true;
}
}
3、MyController
package com.handlers;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.beans.Student;
@org.springframework.stereotype.Controller
@RequestMapping("/test")
public class MyController {
@RequestMapping("register.do")
public ModelAndView handleRequest(@Validated Student student, BindingResult br) {
ModelAndView mv = new ModelAndView();
int errorCount = br.getErrorCount();
if (errorCount > 0) {
FieldError nameError = br.getFieldError("name");
FieldError scoreError = br.getFieldError("score");
FieldError telError = br.getFieldError("tel");
if (nameError != null) {
mv.addObject("nameErrorMSG", nameError.getDefaultMessage());
}
if (scoreError != null) {
mv.addObject("scoreErrorMSG",scoreError.getDefaultMessage());
}
if (telError != null) {
mv.addObject("telErrorMSG",telError.getDefaultMessage());
}
mv.setViewName("/index.jsp");
return mv;
}
mv.addObject("student", student);
mv.setViewName("/welcome.jsp");
return mv;
}
}
4、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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 生成验证器 -->
<bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean>
<!-- 注册mvc注解驱动 -->
<mvc:annotation-driven validator="myValidator"/>
<!-- 注册扫描组件 -->
<context:component-scan base-package="com.handlers"/>
</beans>
5、welcome.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>name = ${student.name }</h1>
<h1>score = ${student.score }</h1>
<h1>telphone = ${student.tel }</h1>
</body>
</html>