一、注册:
先准备一个jsp前端注册页面,把前端数据传给后台
<form action="${pageContext.request.contextPath}/TeacherController?action=register" method="post">
//注册信息:姓名,密码,确认密码,邮箱,性别,备注
</form>
1.利用正则表达式检查信息是否规范。例如用户名:
public class ValidateError {
//检验错误
public static Map<String, String> validateTeacher(Teacher teacher) {
HashMap<String, String> error = new HashMap<>();
//用户名
String name = teacher.getName();
if (name == null || "".equals(name)) {
error.put("name","用户名不能为空");
}else if(!(name.matches("\\w{3,18}"))){
error.put("name","用户名不合法");
}
return error;
}
}
控制层进行验证
String action = req.getParameter("action");
if ("register".equals(action)) {
//接收封装数据
Teacher teacher = new Teacher();
try {
BeanUtils.populate(teacher, req.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//验证功能
Map<String, String> error = ValidateError.validateTeacher(teacher);
if (error.isEmpty()) {
//处理业务
} else {
req.setAttribute("error", error);
req.getRequestDispatcher("/register_teacher.jsp").forward(req, resp);
}
}
将错误信息返回到客户端
<span style="color: red">${error.name}</span>
2.注册时输入密码,再次输入密码时验证是否为空或者两次密码是否一致
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="密码" name="password" id="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="确认密码" name="repassword" id="repassword" onblur="validatepsd()">
<span class="glyphicon glyphicon-log-in form-control-feedback"></span>
</div>
js代码放<script></script>里面
function validatepsd() {
var password = document.getElementById("password").value;
var repassword=document.getElementById("repassword").value;
if(password!="" && repassword!="") {
if (password!=repassword){
alert("两次密码不一样")
}
}else {
alert("密码不能为空")
}
}
3.查看用户名是否已经存在
建一个实体类
public class Teacher implements Serializable{
private Integer id;
private String name;
private String passw