日期:2014-05-16  浏览次数:20602 次

11级_Java_曹建波 03.13 Struts2&ajax实现用户名唯一验证案例

在项目的开发过程中离不开用户名唯一的验证或者邮件唯一的验证.那通过struts2技术是怎么实现,下面以用户名唯一验证案例讲解。

实现效果:

     

当用户名输入框失去焦点的时候,能够实现用户名唯一的验证

步骤:

  1、设计界面代码

并且引入js文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
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 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="${pageContext.request.contextPath }/js/utils.js"></script>
	<script type="text/javascript" src="${pageContext.request.contextPath }/js/regUser.js"></script>
  </head>
  
  <body>
    <div align="center">
    	<h3>注册页面</h3>
    	<s:form action="regUser" namespace="/csdn" theme="simple">
    		用户名:<s:textfield name="username" id="uname"/><span id="cname"></span>
    		<br>
    		密码:<s:password name="userpass" id="ipass" />
    		<br>
    		邮箱:<s:textfield name="useremail" id="uemail" />
    		<br>
    		<s:submit value="注册"/>
    		
    	</s:form>
    </div>
  </body>
</html>


2、在util.js文件中封装

     1、通过id获取dom对象的方法

     2、创建XMLHTTPRequest对象的方法

regUser.js

window.onload = function() {
	var unameDom=$("uname");
	unameDom.onblur=function(){
		var content="name="+unameDom.value;
		var url="./csdn/UserAction_checkName.action?time="+new Date().getTime();
		
		var xhr=createXHR();
		xhr.onreadystatechange=function(){
			if(xhr.readyState==4){
				if(xhr.status==200||xhr.status==304){
					$("cname").innerHTML=xhr.responseText;
				}
			}
			
		}
		xhr.open("POST",url,true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencode