版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载,博客地址:http://blog.csdn.net/xpala https://blog.csdn.net/xpala/article/details/88901988
添加一个表单UserForm模型,用于存储表单的错误信息
提供一个validate方法用于校验所有字段
提供所有属性的get/set方法
简单搭建
package com.xue.form;
import java.util.HashMap;
import java.util.Map;
public class UserForm {
private String username;
private String password;
private String repassword;
private String email;
private String birthday;
Map<String, String> err = new HashMap<String, String>();
public void validate() {
if (username == null || username.trim().length() == 0) {
err.put("username", "用户名不能为空");
}
}
改写RegisterServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
UserForm uForm = new UserForm();
try {
BeanUtils.populate(uForm, request.getParameterMap());
uForm.validate();
if(uForm.getErr().size()>0){
System.out.println(uForm.getErr());
return;
}
} catch (IllegalAccessException | InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
完整写
public class UserForm {
private String username;
private String password;
private String repassword;
private String email;
private String birthday;
Map<String, String> err = new HashMap<String, String>();
public boolean validate() {
if (username == null || username.trim().length() == 0) {
err.put("username", "用户名不能为空");
}
// w:[A-Za-Z_09]
if (!username.matches("\\w{5,15}")) {
err.put("username", "用户名长度5~15");
}
if (password == null || password.trim().length() == 0) {
err.put("password", "密码不能为空");
}
if (!password.matches("\\w{6,9}")) {
err.put("password", "密码长度6~9");
}
if (!password.equals(repassword)) {
err.put("repassword", "两次密码需一致");
}
if (email == null || email.trim().length() == 0) {
err.put("email", "邮箱不能为空");
}
if (!email.matches("^[A-Za-z0-9][\\w\\-\\.]{3,12}@([\\w\\-]+\\.)+[\\w]{2,3}$")) {
err.put("email", "邮箱格式要正确");
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
sdf.parse(birthday);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
err.put("birthday", "日期格式2018-01-11");
}
return err.size()==0;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
UserForm uForm = new UserForm();
try {
BeanUtils.populate(uForm, request.getParameterMap());
uForm.validate();
if(!uForm.validate()){
System.out.println(uForm.getErr());
return;
}
} catch (IllegalAccessException | InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}