实现了Validator接口,前端页面使用<form:errors>标签显示属性的错误信息
1.javaBean
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
2.前端登陆页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri= "http://www.springframework.org/tags/form" prefix="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=UTF-8">
<title>测试Validator接口验证</title>
</head>
<body>
<h3>登录页面</h3>
<!-- 绑定user -->
<form:form modelAttribute="user" method="post" action="tologin" >
<table>
<tr>
<td>登录名:</td>
<td><input type="text" name="username" id="username" /></td>
<!-- 显示loginname属性的错误信息 -->
<td><form:errors path="username" cssStyle="color:red"/></td>
</tr>
<tr>
<td>密码:</td>
<td><form:input path="password"/></td>
<!-- 显示password属性的错误信息 -->
<td><form:errors path="password" cssStyle= "color:red"/></td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
</tr>
</table>
</form:form>
</body>
</html>
3.MyValidator类,实现了Validator接口
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class MyValidator implements Validator {
public boolean supports(Class<?> clazz) {
// TODO Auto-generated method stub
return User.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
// TODO Auto-generated method stub
User user = (User)target;
ValidationUtils.rejectIfEmpty(errors, "username", "U404", "用户名不能为空");
ValidationUtils.rejectIfEmpty(errors, "password", null, "密码不能为空");
if(user.getUsername().length() > 10){
errors.rejectValue("username", "U405", "用户名长度不能超过10个字符");
}
if(user.getPassword().length() < 6){
errors.rejectValue("password", null, "密码长度不能小于6个字符");
}
}
4.Controller类
package com.controller;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bean.User;
import com.validator.MyValidator;
@Controller
public class UserController {
@Autowired
@Resource
private MyValidator validator;
@RequestMapping("/{login}")
public String login(@PathVariable String login, ModelMap mm){
mm.addAttribute("user", new User());
return login;
}
@RequestMapping("/tologin")
//在需要校验的属性前面加@Validated
//BindingResult属性必须要放在@Validated注解属性的后面,否则spring会在校验不通过时直接抛出异常
public String tologin(@Validated User user, BindingResult result){
if(result.hasErrors()){
return "login";
}
return "success";
}
@InitBinder
public void initBinder(WebDataBinder binder){
binder.setValidator(validator);
}
/*@RequestMapping("/tologin")
//在需要校验的属性前面加@Validated
//Errors属性必须要放在@Validated注解属性的后面
public String tologin(@Validated User user, Errors errors){
validator.validate(user, errors);
if(errors.hasErrors()){
return "login";
}
return "success";
}*/
}
上面两种@RequestMapping("/tologin")映射的作用效果一样
5.配置文件:
<?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:p="http://www.springframework.org/schema/p"
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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan base-package="com.controller"/>
<context:component-scan base-package="com.validator"/>
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<!-- 后缀 -->
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>