本文说的是在登录页面中使用js进行正则验证并使用ajax进行用户ID的数据库验证,另外也加入键盘监听。
先看一下登录的jsp页面代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="org.ml.drp.sysmgr.domain.*"%> <%@ page import="org.ml.drp.sysmgr.manager.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; String command = request.getParameter("command"); if("addUser".equals(command)){ if(UserManager.getInstance().findUserById(request.getParameter("userId"))!=null){ out.write("<font color=red>用户"+request.getParameter("userId")+"已经存在</font>"); }else{ User user = new User(); user.setUserId(request.getParameter("userId")); user.setUserName(request.getParameter("userName")); user.setPassword(request.getParameter("password")); user.setContactTel(request.getParameter("contactTel")); user.setEmail(request.getParameter("email")); if(UserManager.getInstance().addUser(user)){ out.write("<font color=red>用户信息添加成功</font>"); }else{ out.write("<font color=red>添加用户过程中出现异常</font>"); } } } %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加用户</title> <link rel="stylesheet" href="../style/drp.css"> <script src="../script/client_validate.js"></script> <script type="text/javascript"> function goBack() { window.self.location="user_maint.html"; } function addUser() { //验证用户代码 var userId = document.getElementById("userId"); var userIdValue = userId.value; if(!(/^[a-zA-Z]+[a-zA-Z0-9]*$/.test(trim(userIdValue))&&/^[a-zA-Z0-9]{4,6}$/.test(trim(userIdValue)))){ alert("用户代码必须以字母开头,并且为4-6位!"); userId.focus(); userId.select(); return; } /* if(trim(userIdValue)==""){ alert("用户代码不能为空 !"); userId.focus(); userId.select(); return; } if(trim(userIdValue).length<4){ alert("用户代码至少为4位!"); userId.focus(); userId.select(); return; } */ //验证用户名 var userName = document.getElementById("userName"); var userNameValue = userName.value; if(trim(userNameValue)==""){ alert("用户名不能为空 !"); userName.focus(); userName.select(); return; } //验证密码 var password = document.getElementById("password"); var passwordValue = password.value; if(trim(passwordValue)==""){ alert("密码不能为空 !"); password.focus(); password.select(); return; } if(trim(passwordValue).length<6){ alert("用户密码至少6位!"); password.focus(); password.select(); return; } //验证电话 var contactTel = document.getElementById("contactTel"); var contactTelValue = contactTel.value; if(trim(contactTelValue)!=""){ var pattern=/^(13[0-9]|15[0-9]|18[8|9])\d{8}$/; var flag = pattern.test(contactTelValue); if(!flag){ alert("联系电话格式不正确!"); contactTel.focus(); return; } } //验证邮箱 var email = document.getElementById("email"); var emailValue = email.value; if(trim(emailValue)!=""){ var pattern1 = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; var flag = pattern1.test(emailValue); if(!flag) { alert("Email地址不合法!"); email.focus(); email.select(); return; } } var form = document.getElementById("userForm"); form.submit(); } function init(){ document.getElementById("userId").focus();//第一个输入框获取得焦点 } //键盘按下监听 function keyPress(nextId){ if(window.event.keyCode==13){//当按下的是Enter键的时候 document.getElementById(nextId).focus(); } } var xmlHttp; function createXMLHttpRequest(){ if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlHttp = new window.ActiveXObject("Microsoft.XMLHTTP"); } } /* //方式一 function checkUserId(userId){ if(trim(userId.value)!=""){ createXMLHttpRequest();//创建Ajax核心对象XMLHttpRequest var url = "user_validate.jsp?userId="+trim(userId.value) + "&time="+new Date().getTime(); //设置请求方式为get,设置 url请求,设置为异步提交 xmlHttp.open("get",url,true); //将方法地址赋值给属性 xmlHttp.onreadystatechange=callback; //将设置的信息发送给Ajax引擎 xmlHttp.send(null); }{ document.getElementById("userIdSpan").innerHTML="<font color='red'>用户代码不能为空</font>"; } } function callback(){ if(xmlHttp.readyState==4){//响应完成 if(xmlHttp.status==200){//请求成功 var userIdSpan = document.getElementById("userIdSpan"); userIdSpan.innerHTML= xmlHttp.responseText }else{ alert("用户代码验证请求失败") } } } */ //方式二 function checkUserId(userId){ if(trim(userId.value)!=""){ createXMLHttpRequest();//创建Ajax核心对象XMLHttpRequest var url = "user_validate.jsp?userId="+trim(userId.value) + "&time="+new Date().getTime(); //设置请求方式为get,设置 url请求,设置为异步提交 xmlHttp.open("get",url,true); //将方法地址赋值给属性 xmlHttp.onreadystatechange=function(){//使用匿名对象进行 if(xmlHttp.readyState==4){//响应完成 if(xmlHttp.status==200){//请求成功 var userIdSpan = document.getElementById("userIdSpan"); userIdSpan.innerHTML= xmlHttp.responseText }else{ alert("用户代码验证请求失败") } } }; //将设置的信息发送给Ajax引擎 xmlHttp.send(null); }{ document.getElementById("userIdSpan").innerHTML="<font color='red'>用户代码不能为空</font>"; } } </script> </head> <body class="body1" onload="init()"> <form action="#" name="userForm" target="_self" id="userForm" method="post"> <div align="center"> <table width="95%" border="0" cellspacing="2" cellpadding="2"> <tr> <td> <input type="hidden" name="command" value="addUser"> </td> </tr> </table> <table width="95%" border="0" cellspacing="0" cellpadding="0" height="25"> <tr> <td width="522" class="p1" height="25" nowrap> <img src="../images/mark_arrow_03.gif" width="14" height="14"> <b>系统管理>>用户维护>>添加</b> </td> </tr> </table> <hr width="97%" align="center" size=0> <table width="95%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="22%" height="29"> <div align="right"> <font color="#FF0000">*</font>用户代码: </div> </td> <td width="78%"> <input name="userId" type="text" class="text1" id="userId" size="10" maxlength="10" onkeypress="keyPress('userName')" onblur="checkUserId(this)"> <span id="userIdSpan" ></span> </td> </tr> <tr> <td height="26"> <div align="right"> <font color="#FF0000">*</font>用户名称: </div> </td> <td> <input name="userName" type="text" class="text1" id="userName" size="20" maxlength="20" onkeypress="keyPress('password')"> </td> </tr> <tr> <td height="26"> <div align="right"> <font color="#FF0000">*</font>密码: </div> </td> <td> <label> <input name="password" type="password" class="text1" id="password" size="20" maxlength="20" onkeypress="keyPress('contactTel')"> </label> </td> </tr> <tr> <td height="26"> <div align="right"> 联系电话: </div> </td> <td> <input name="contactTel" type="text" class="text1" id="contactTel" size="20" maxlength="20" onkeypress="keyPress('email')"> </td> </tr> <tr> <td height="26"> <div align="right"> email: </div> </td> <td> <input name="email" type="text" class="text1" id="email" size="20" maxlength="20" onkeypress="keyPress('btnAdd')"> </td> </tr> </table> <hr width="97%" align="center" size=0> <div align="center"> <input name="btnAdd" class="button1" type="button" id="btnAdd" value="添加" onClick="addUser()"> <input name="btnBack" class="button1" type="button" id="btnBack" value="返回" onClick="goBack()" /> </div> </div> </form> </body> </html>执行验证数据库的时候的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="org.ml.drp.sysmgr.manager.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'user_validate.jsp' starting page</title> </head> <body> <% String userId = request.getParameter("userId").trim(); System.out.println(userId); if(UserManager.getInstance().findUserById(userId)!=null){ out.print("<font color='red'>用户代码已存在</font>"); }else{ out.print("<font color='green'>用户代码可使用</font>"); } %> </body> </html>
数据库的管理操作类如下:
package org.ml.drp.sysmgr.manager; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import org.ml.drp.sysmgr.domain.User; import org.ml.drp.util.DbUtil; public class UserManager { private static UserManager instance = null; /** * 私有化的无参构造方法 */ private UserManager(){ } /** * 取得UserManager实例化对象 * @return */ public static UserManager getInstance(){ if(instance==null){ instance = new UserManager(); } return instance; } /** * 添加用户信息 * @param user * @return */ public boolean addUser(User user){ boolean flag = false; Connection conn = null; PreparedStatement pstmt = null; String sql = "insert into t_user(user_id,user_name,password,contact_tel,email,create_date) values(?,?,?,?,?,?)"; try { conn = DbUtil.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUserId()); pstmt.setString(2, user.getUserName()); pstmt.setString(3, user.getPassword()); pstmt.setString(4, user.getContactTel()); pstmt.setString(5, user.getEmail()); pstmt.setTimestamp(6, new Timestamp(new Date().getTime())); if(pstmt.executeUpdate()>0){ flag = true;//添加成功 } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DbUtil.close(conn);//关闭数据库连接 DbUtil.close(pstmt);//关闭prepareStatementd对象 } return flag; } /** * 根据用户ID查找用户 * @param userId * @return */ public User findUserById(String userId){ User user = null; String sql = "select user_name,password,contact_tel,email,create_date from t_user where user_id=?"; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DbUtil.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, userId); rs = pstmt.executeQuery(); if(rs.next()){ user = new User(); user.setUserId(userId); user.setUserName(rs.getString(1)); user.setPassword(rs.getString(2)); user.setContactTel(rs.getString(3)); user.setEmail(rs.getString(4)); user.setCreateDate(rs.getTimestamp(5)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DbUtil.close(conn);//关闭数据库连接 DbUtil.close(pstmt);//关闭prepareStatementd对象 } return user; } }这里只是进行了简单的记录,只粘贴了代码,没做过多说明,有兴趣的可以慢慢看吧,还有如果要看数据库实现数据库连接操作类的代码的可以看看这篇 http://blog.csdn.net/cselmu9/article/details/7844235文章,这里面有完整数据库连接操作代码,这里就不贴出来了。