用户注册信息的验证与数据回显

来源:互联网 发布:赈灾晚会的数据统计 编辑:程序博客网 时间:2024/04/30 13:15


  半成品   带完善


用户注册信息的验证与数据回显
注:  需要数据库驱动jar包,BeanUtils.jar,jstl.jar,stand.jar
         熟悉各种表单类型数据的回显与验证
         会写FormBeanUtil工具类
         会在一个web.controller类中处理各种业务
-------------------------------------------------------------------------------------------------------
注册表单
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.itcast.cn/myfn" prefix="myfn"%>  


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
          <title>用户注册</title>        
          <meta http-equiv="pragma" content="no-cache">
          <meta http-equiv="cache-control" content="no-cache">
          <meta http-equiv="expires" content="0">    
  </head>
  
  <body>
 
        <form action="${pageContext.request.contextPath}/servlet/ControllerServlet?operation=regist" method="post">
                <table border="1" width="50%">
                        <tr>
                                <td><span style="color: red;">*</span>用户名(3~8位字母)</td>
                                <td>
                                        <!-- value用来数据回显 -->
                                        <input type="text" name="username" value="${formBean.username}" />${formBean.errors.username}      
                                </td>      
                        </tr>
                        <tr>
                                <td><span style="color: red;">*</span>密码(3~8位数字)</td>
                                <td>
                                        <input type="password" name="password" value="${formBean.password}" />${formBean.errors.password} 
                                </td>
                        </tr>
                        <tr>
                                <td><span style="color: red;">*</span>确认密码</td>
                                <td>
                                        <input type="password" name="repassword" value="${formBean.repassword}" />${formBean.errors.repassword}
                                </td>
                        </tr>
                        <tr>
                                <td>性别</td>
                                <td>
                                        <input type="radio" name="gender" value="1" ${formBean.gender=="1"?"checked='checked'":""} />男                     
                                        <input type="radio" name="gender" value="0" ${formBean.gender=="0"?"checked='checked'":""}/>女
                                </td>
                        </tr>
                        <tr>
                                <td><span style="color: red;">*</span>邮箱</td>
                                <td>
                                        <input type="text" name="email" value="${formBean.email}" />${formBean.errors.email}
                                </td>
                        </tr>
                        <tr>
                                <!-- 待引入日期选择框插件 -->
                                <td><span style="color: red;">*</span>出生日期</td>  
                                <td>
                                        <input type="text" name="birthday" value="${formBean.birthday}" />${formBean.errors.birthday}
                                </td>
                        </tr>                       
                        <tr>
                              <td>爱好</td>
                              <td>
                                      <input type="checkbox" name="hobbies" value="吃饭" ${myfn:contains(formBean.hobbies,'吃饭')?"checked='checked'":""}/>吃饭                             
                                      <input type="checkbox" name="hobbies" value="睡觉" ${myfn:contains(formBean.hobbies,'睡觉')?"checked='checked'":""}/>睡觉
                                      <input type="checkbox" name="hobbies" value="打豆豆" ${myfn:contains(formBean.hobbies,'打豆豆')?"checked='checked'":""}/>打豆豆
                              </td>
                      </tr>
                      <tr>
                              <td>描述</td>
                              <td>
                                      <textarea name="description" rows="6" cols="48" >${formBean.description}</textarea>
                              </td>
                      </tr>
                      <tr>
                                <td colspan="2">
                                        <input type="submit" value="注册" />  
                                </td>
                        </tr>            
                </table>                
        </form>


  </body>
</html>


-------------------------------------------------------------------------------------------------------
针对hobbies中的数据回显  自定义的EL函数
// 1  创建函数
public class MyFunctions {
        public static boolean contains(String[] strs,String str){
                boolean result = false;
                if(strs!=null&&strs.length>0){
                      for(String s: strs){
                              if(s.equals(str)){
                                      result = true;
                                      break;
                              }
                        }
                  }
          return result;
          }
}


// 2  在WEB-INF下建立myfn.tld的xml文件  更改配置信息
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    <tlib-version>1.0</tlib-version>
    <short-name>myfn</short-name>
    <uri>http://www.itcast.cn/myfn</uri>
    <function>
        <name>contains</name>
<function-class>cn.itcast.el.functions.MyFunctions</function-class>
<function-signature>boolean contains( java.lang.String[],java.lang.String )</function-signature>
    </function>
</taglib>
// 3  在jsp页面中导入配置文件myfn.tld
<%@ taglib uri="http://www.itcast.cn/myfn" prefix="myfn"%>  


-------------------------------------------------------------------------------------------------------
formBean: 与表单对应,所有字段都是String类型的,封装了表单提交的信息
public class UserFormBean {


        private String username;
        private String password;
        private String repassword;
        private String gender;
        private String email;
        private String birthday;      
        private String[] hobbies;
        private String description;
        // 存放错误信息: key: 字段名   value:错误消息 
        private Map<String, String> errors = new HashMap<String, String>();   
        
       // 一系列的setter和getter属性(注: 不需要errors的setter属性)
        
        // 验证字段
        public boolean validate(){
                // 正则: java.util.regex.Pattern查
                
                // 验证用户名: 3~8位字母
                if(username==null || username.trim().equals("")){
                        errors.put("username", "用户名不能为空");
                }else{
                        if(!username.matches("[a-zA-Z]{3,8}")){
                                errors.put("username", "用户名必须是3~8位的字母");
                        }
                }
          
                // 验证密码: 3~8位数字
                if(password==null || password.trim().equals("")){
                        errors.put("password", "密码不能为空");
                }else{
                        if(!password.matches("\\d{3,8}")){
                                errors.put("password", "密码必须是3~8位的数字");
                        }
                }
                
                // 重复密码
                if(repassword!=null){
                        if(!repassword.equals(password)){
                                errors.put("repassword", "两次密码必须一致");
                        }
                }else{
                        errors.put("repassword", "请输入重复密码");
                }


                // 邮箱
                if(email==null || email.trim().equals("")){
                        errors.put("email", "邮箱不能为空");
               }else{
                        if(!email.matches("\\w+@\\w+(\\.\\w+)+")){
                                errors.put("email", "请输入正确的邮箱");
                        }
                }
                
                // 生日
                if(birthday==null || birthday.trim().equals("")){
                        errors.put("birthday", "出生日期不能为空");
                }else{
                        DateLocaleConverter dlc = new DateLocaleConverter();
                        try{
                                dlc.convert(birthday);
                        }catch(Exception e){
                                errors.put("birthday", "请输入正确的日期");
                        }
                }
                
                // 若errors集合为空,即没有错误,返回true
                return errors.isEmpty();
        }

}
-------------------------------------------------------------------------------------------------------
FormBeanUtil工具类: 将form发送的请求的信息封装到类中
public class WebUtil {
        public static <T>T fillData(HttpServletRequest request, Class<T> clazz){
                try{
                        T bean = clazz.newInstance();
                        BeanUtils.populate(bean, request.getParameterMap());
                        return bean;
                }catch (Exception e){
                        throw new RuntimeException(e);
                }
        }
}
-------------------------------------------------------------------------------------------------------
Servlet控制层
public class ControllerServlet extends HttpServlet {


        private BusinessService s = new BusinessServiceImpl();
        
        public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                String encoding = "UTF-8";
                request.setCharacterEncoding(encoding);
                response.setCharacterEncoding(encoding);
                response.setContentType("text/html;charset="+encoding);
                
                String operation = request.getParameter("operation");
                if("regist".equals(operation)){
                  regist(request,response);
                }
        }


        // 完成注册
        private void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // 验证--填充模型: 把用户的数据填充到模型层javaBean中
                UserFormBean formBean = null;
                try{
                        // 把数据(字段和错误信息error)封装到一个FormBean(与form表单对应)中,利用FormBean进行验证
                        formBean = FormBeanUtil.fillData(request,UserFormBean.class);                           
                        // 验证不通过:数据回显
                        if(!formBean.validate()){
                                request.setAttribute("formBean", formBean);
                                request.getRequestDispatcher("/regist.jsp").forward(request, response);
                                return;
                        }else{
                                // 验证通过: 填充模型FormBean ---> user 类型转换:String-->Other  Other-->String      
                                User user = new User();
                                ConvertUtils.register(new DateLocaleConverter(), Date.class);                             
                                // 参数:  目标  源
                                BeanUtils.copyProperties(user, formBean);
                                
                                // 对爱好进行单独处理
                                String[] hobbies = formBean.getHobbies();
                                if(hobbies!=null&&hobbies.length>0){
                                        StringBuffer sb = new StringBuffer();
                                        for(int i=0;i<hobbies.length;i++){
                                                if(i>0){
                                                        sb.append(",");
                                                }
                                                sb.append(hobbies[i]);
                                        }
                                        c.setHobby(sb.toString());
                                }
                                
                                // 把信息存到数据库中(用户名可能存在)
                                s.register(user);
                                request.setAttribute("message", "注册成功");
                                request.getRequestDispatcher("/message.jsp").forward(request, response);
                        }
                }catch(UserExistException e){
                        formBean.getErrors().put("username", "用户名已存在"); // 给errors错误集合新增元素
                        // 数据回显
                        request.setAttribute("formBean", formBean);
                        request.getRequestDispatcher("/regist.jsp").forward(request, response);
                        return;
                }catch(Exception e){
                        e.printStackTrace();   // 后台日志记录异常
                        request.setAttribute("message", "服务器忙");
                        request.getRequestDispatcher("/message.jsp").forward(request, response);
                }
        }


        public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                doGet(request, response);
        }


}


-------------------------------------------------------------------------------------------------------


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
          <title>全局消息页面</title>   
          <meta http-equiv="pragma" content="no-cache">
          <meta http-equiv="cache-control" content="no-cache">
          <meta http-equiv="expires" content="0">    
  </head> 
  <body>
          ${message}
  </body>
</html>


-------------------------------------------------------------------------------------------------------










0 0