SimpleFromController表单数据验证Validator
project结构
一、LoginForm.java
public class LoginForm {
private String username;
private String password;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
二、 LoginController.ava
public class LoginController extends SimpleFormController {
public LoginController() {
setCommandClass(LoginForm.class);
}
@Override
protected ModelAndView onSubmit(
Object command) throws Exception {
LoginForm form = (LoginForm) command;
if("root".equals(form.getUsername()) &&
"123456".equals(form.getPassword())) {
Map model = new HashMap();
model.put("username",form.getUsername());
model.put("password",form.getPassword());
return new ModelAndView(getSuccessView(),model);
}
else {
Map model = new HashMap();
model.put("command",command);
return new ModelAndView(getFormView(),model);
}
}
三、表单数据验证类FormValidator
public class FormValidator implements Validator{
public boolean supports(Class clazz) {
return clazz.equals(LoginForm.class);
}
public void validate(Object obj, Errors errors) {
LoginForm loginForm=(LoginForm)obj;
String name = loginForm.getUsername();
System.out.println(name);
String password = loginForm.getPassword();
System.out.println(password);
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username",
"required.username", "用户名必须填写");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
"required.password", "密码不能为空");
}
四、配置
<bean id="loginValidator"
class = "onlyfun.caterpillar.FormValidator">
</bean>
<bean id="loginController"
class="onlyfun.caterpillar.LoginController">
<property name="validator" >
<ref bean="loginValidator"/>
</property>
<property name="successView">
<value>success</value>
</property>
<property name="formView">
<value>login</value>
</property>
</bean>
五、jsp中显示错误信息
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<body>
<form:form method="post" action="login.do">
用户名:<form:input path="username" />
<font color="red"><form:errors path="username" /></font>
<br>
密 码:<form:password path="password" />
<font color="red"><form:errors path="password" /></font>
<br>
<input type="submit" value="登录" />
<input type="reset" value="重置" />
</form:form>
</body>