首先,在pom.xml中添加hibernate.validator的支持
<!-- hibernate.validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
表单提交页面user_add.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>add user</title>
</head>
<body>
<form:form id="form" method="post"
modelAttribute="validUserBean">
添加用户
<form:label path="account">账号:</form:label>
<form:input path="account" />
<form:errors path="account" />
<form:label path="password">密码:</form:label>
<form:input path="password" />
<form:errors path="password" />
<button type="submit">添加</button>
<button type="reset">重置</button>
<c:out value="${show}"></c:out>
</form:form>
</body>
</html>
新建一个用于验证的Bean:ValidUserBean
package com.worldless.admin.controller;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
@Component("ValidUserBean")
public class ValidUserBean {
@NotEmpty
private String account;
@NotEmpty
@Length(min=6,max=16)
private String password;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
来修改controller,
package com.worldless.admin.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class AdminController {
@Autowired
private ValidUserBean validUserBean;
//通过url访问新增页面
@RequestMapping(value = "admin/add", method = RequestMethod.GET)
public String userNew(Model model) {
model.addAttribute("validUserBean", validUserBean);
return "admin/user_add";
}
//点击按钮提交时
@RequestMapping(value = "admin/add", method = RequestMethod.POST)
public String userAdd(
@ModelAttribute("validUserBean") @Valid ValidUserBean validUserBean,
BindingResult result, Model model) {
if (!result.hasErrors()) {
model.addAttribute("show", "ok");
}
return "admin/user_add";
}
}
访问页面
输入错误时显示
输入正确时显示