日期:2014-05-16  浏览次数:20389 次

SpringMVC 使用JSR-303进行校验 @Valid

?

一、准备校验时使用的JAR

?????

? 说明:

???????? validation-api-1.0.0.GA.jar是JDK的接口;

???????? hibernate-validator-4.2.0.Final.jar是对上述接口的实现。

?

------------------------------------------------------------

新增一个测试的pojo bean ,增加jsr 303格式的验证annotation

Java代码 复制代码 ?收藏代码
	@NotEmpty
	private String userName;
	@Email
	private String email;


在controller 类中的handler method中,对需要验证的对象前增加@Valid 标志

Java代码 复制代码 ?收藏代码
	@RequestMapping("/valid")
	public String valid(@ModelAttribute("vm") [color=red]@Valid[/color] ValidModel vm, BindingResult result) {
		if (result.hasErrors()) {
			return "validResult";
		}

		return "helloworld";
	}


增加显示验证结果的jsp如下

Jsp代码 复制代码 ?收藏代码
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
<title>Reservation Form</title>
<style>
.error {
	color: #ff0000;
	font-weight: bold;
}
</style>
</head>

<body>
	<form:form method="post" modelAttribute="vm">
		<form:errors path="*" cssClass="error" />
		<table>
			<tr>
				<td>Name</td>
				<td><form:input path="userName" />
				</td>
				<td><form:errors path="userName" cssClass="error" />
				</td>
			</tr>
			<tr>
				<td>email</td>
				<td><form:input path="email" />
				</td>
				<td><form:errors path="email" cssClass="error" />
				</td>
			</tr>
	
			<tr>
				<td colspan="3"><input type="submit" />
				</td>
			</tr>
		</table>
	</form:form>
</body>
</html>


访问 http://localhost:8080/springmvc/valid?userName=winzip&email=winzip
查看验证结果。
二:自定义jsr 303格式的annotation
参考hibernate validator 4 reference 手册中3.1节,增加一个自定义要求输入内容为定长的annotation验证类
新增annotation类定义

Java代码 复制代码 ?收藏代码
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = FixLengthImpl.class)
public @interface FixLength {

	int length();
	String message() default "{net.zhepu.web.valid.fixlength.message}";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};
}


及具体的验证实现类如下

Java代码 复制代码