本文主要是介绍JavaWeb学习-MVC基础开发系列-5-用户注册校验实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这篇来看看用户注册表单中,如果用户数输入内容和字段要求不符合,弹出对应错误消息提醒。这个过程要怎么实现呢,
1.新写一个实体类
这个实体类,就是一个UserForm.java,里面包含注册表单的一切属性,还有一个map集合,用来存放各种错误提示。
package com.anthony.domain;import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;public class UserForm implements Serializable {private String username;private String password;private String repassword;private String email;private String birthday;private int id;private Map<String, String> msg = new HashMap<String, String>();public boolean validate() {//校验用户名输入if("".equals(username)) {msg.put("username", "用户名不能为空");}else if(!username.matches("\\w{3,8}")) {msg.put("username", "用户名为3—8位字母组成");}//校验密码输入if("".equals(password)) {msg.put("password", "密码不能为空");}else if(!password.matches("\\d{3,8}")) {msg.put("password", "密码为3—8位数字组成");}//校验两次密码输入是否一致if(!repassword.equals(password)) {msg.put("repassword", "两次输入密码不一致");}//邮件规则正则if("".equals(email)) {msg.put("email", "邮箱不能为空");}else if(!email.matches("^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$")) {msg.put("email", "不是有效的邮箱格式");}//生日输入规则if("".equals(birthday)) {msg.put("birthday", "生日不能为空");}else {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");try {sdf.parse(birthday);} catch (ParseException e) {msg.put("birthday", "请输入正确邮箱格式");}}return msg.isEmpty();// 当集合为空,全部条件验证通过,返回true}public Map<String, String> getMsg() {return msg;}public void setMsg(Map<String, String> msg) {this.msg = msg;}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;}public String getRepassword() {return repassword;}public void setRepassword(String repassword) {this.repassword = repassword;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}public int getId() {return id;}public void setId(int id) {this.id = id;}}
这里提醒一下,如果msg不写成属性字段,然后添加set和get方法,那么会报错误:with root cause
javax.el.PropertyNotFoundException: Property [msg] not found on type [com.anthony.domain.UserForm]
2.修改RegServlet.java
package com.anthony.web.servlet;import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;import com.anthony.domain.User;
import com.anthony.domain.UserForm;
import com.anthony.service.UserService;
import com.anthony.service.impl.UserServiceImpl;public class RegServlet extends HttpServlet {protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");//获取表单数据UserForm uf = new UserForm();try {BeanUtils.populate(uf, req.getParameterMap());} catch (Exception e1) {e1.printStackTrace();}if(!uf.validate()) { //如果msg map集合不为空,说明输入条件不符合要求req.setAttribute("uf", uf);req.getRequestDispatcher("/register.jsp").forward(req, resp);return; //出错,不需要往下走注册流程,所以这里需要return空来终止代码往下执行}User user = new User();try {//解决日期是字符串的异常ConvertUtils.register(new DateLocaleConverter(), Date.class);BeanUtils.populate(user, req.getParameterMap());//调用业务层方法/逻辑UserService us = new UserServiceImpl();us.register(user);} catch (Exception e) {e.printStackTrace();}//分发转向resp.getWriter().write("注册成功,2秒之后跳转到主页");resp.setHeader("refresh", "2;url="+req.getContextPath()+"/index.jsp");}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}}
3.修改register.jsp
<%@ 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>注册</title>
</head>
<body><form action="${pageContext.request.contextPath}/servlet/regServlet" method="post">用户名:<input type="text" name="username" value="${uf.username}"/>${uf.msg.username}<br/>密码:<input type="password" name="password"/>${uf.msg.password}<br/>确认密码:<input type="password" name="repassword"/>${uf.msg.repassword}<br/>邮箱:<input type="text" name="email" value="${uf.email}"/>${uf.msg.email}<br/>生日:<input type="text" name="birthday" value="${uf.birthday}"/>${uf.msg.birthday}<br/><input type="submit" value="注册"></form>
</body>
</html>
4.测试效果
4.1 全部为空
4.2 名称和密码不符合3-8规则
4.3 生日不符合规则
上面邮箱格式判断明显有问题,说明这个正则表达式写的有问题。以后实际开发中,可以网上搜一下,别人是如何写邮箱地址判断的正则表达式。
这篇关于JavaWeb学习-MVC基础开发系列-5-用户注册校验实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!