现在的位置: 首页 > web前端 > 正文

【垃圾菜鸟笔记】ajax +用户注册小小实例

2018年05月16日 web前端 ⁄ 共 9165字 ⁄ 字号 评论关闭

userAction.java

package xxx.user.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpSession;
import javax.swing.Action;

import xxx.common.BaseAction;
import xxx.user.pojo.Conuser;
import xxx.user.service.userService;

import com.opensymphony.xwork2.ModelDriven;

public class userAction extends BaseAction implements ModelDriven<Conuser> {

	public userAction() {
	}

	private Conuser conuser = new Conuser();

	private userService service;

	public Conuser getConuser() {
		return conuser;
	}

	public void setConuser(Conuser conuser) {
		this.conuser = conuser;
	}

	public void setService(userService service) {
		this.service = service;
	}

	public Conuser getModel() {

		return conuser;
	}

	public userService getService() {
		return service;
	}

	public String check() throws IOException {

		// Serverlet根据请求的参数,验证完成后,以xml格式写下验证信息。
		// 供JSP页面的XMLHttpRequest对象读取。
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");

		// 验证用户名
		boolean ck = service.checkUserName(conuser);
		// 根据返回的结果,写下相应的XML信息。
		if (ck) {
			response.getWriter().write("<message>1</message>"); // 用户名不存在

			return null;

		} else {
			response.getWriter().write("<message>0</message>"); // 用户名存在

			return null;

		}
		// return "check";
	}

	public String addUser() throws IOException {

		service.addUser(conuser);

		return "add";

	}

	public String login() throws IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		System.out.println(conuser.getUserName());
		if (conuser.getUserLevel() != 0) {

			HttpSession session = request.getSession();
			session.setAttribute("userName", conuser.getUserName());
			session.setAttribute("userLevel", conuser.getUserLevel());
			return SUCCESS;
		}
		// 返回登陆标识
		int flag = service.checkLogin(conuser);
		if (flag == 0) {
			out.println("<script>alert('用户名或密码不正确!');history.back();</script>");
			return null;
		} else {
			// 在session范围存储键值对
			HttpSession session = request.getSession();
			session.setAttribute("userName", conuser.getUserName());
			session.setAttribute("userLevel", flag);
			return SUCCESS;

		}

	}
}

addUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	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 'addUser.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="js/check.js" />
		<script type="text/javascript" src="ja/jquery-1.7.2.js"></script>
<script type="text/javascript">
	
  
      function createXml(){  
    if(window.XMLHttpRequest){  
        xmlHttp = new XMLHttpRequest();  
    }else if(window.ActiveXObject){  
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
    }  
}  
//验证用户名方法  
function checkUserNameAction(userName){  
            var nameField = userName.value;  
            if(nameField.length==0)  
                return false;  
                     var url="user/check.action?userName="+'\"'+nameField+'\"'+'&_dc='+new Date().getTime();///加缓存防止ie下的get缓存;
                 //  alert(url);
         //var url="check.action?userName="+nameField;
           checkUserNameMsg.innerHTML = "检测中,请等待...";  
            createXml();  
            if(xmlHttp){  
                xmlHttp.open("GET",url,true);           //注册处理事件的url  
                xmlHttp.onreadystatechange = callback;  //注册回传函数  
                xmlHttp.send(null);                     //发送请求  
            }  
}//end checkUserNameAction();  
//回传方法  
function callback(){  
    if(xmlHttp.readyState == 4){  
        if(xmlHttp.status == 200){  
        	//alert('请求已发出');
          showResult();//回传处理  
        }  
    }  
}  
//显示检测结果  
function showResult() {  
	//alert( xmlHttp.responseText);
	  //  var message1 = xmlHttp.responseText.getElementsByTagName("messages")[0];  
	
   var message = xmlHttp.responseXML.getElementsByTagName("message")[0];  //;   
    var msg = message.firstChild.data;  
    
    if(msg=="1"){  
        nameEnable = true;  
      //  alert('keyishiyong ');
        checkUserNameMsg.innerHTML = "<font color='green' size='2px'><b>用户名可以使用</b></font>"; 
        check();
        return true;  
    }else if(msg=="0"){  
        nameEnable = false;
            //    alert('bukeyishiyong ');
        	document.addUser.userName.focus();
		document.addUser.userName.select();
        checkUserNameMsg.innerHTML = "<font color='red'  size='2px'><B>&nbsp;用户名已存在,请重新输入</B></font>";  
          
        return false;  
    }  
      
}


</script>


	</head>
	<!-- oncontextmenu="return false" ondragstart="return false"
		onselectstart="return false"  -->
	<body>
		<div>
			<form action="<%=request.getContextPath()%>/user/addUser.action"
				method="post" id="addUser" name="addUser">
				<table width="600" border="0" align="center" cellpadding="0"
					cellspacing="0">
					<tr>
						<td height="50" colspan="5" align="center" bgcolor="#CCCCCC">
							<blockquote>
								<blockquote>
									<blockquote>
										<p>
											<strong>用户注册</strong>
										</p>
									</blockquote>
								</blockquote>
							</blockquote>
						</td>
					</tr>
					<tr>
						<td width="39" height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td width="175" height="50" align="right" bgcolor="#E4E4E4">
							用 户 名
						</td>
						<td height="50" colspan="2" bgcolor="#E4E4E4">
							<input name="userName" type="text" id="userName" size="24"
								maxlength="20" onBlur="checkUserNameAction(this);" >
						</td>
						<td height="50" bgcolor="#E4E4E4">
							<span id="checkUserNameMsg"></span>
						</td>
					</tr>
					<tr>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" align="right" bgcolor="#E4E4E4">
							密 码
						</td>
						<td height="50" colspan="2" bgcolor="#E4E4E4">
							<input name="userPwd" type="text" id="userPwd" size="24"
								maxlength="20">
						</td>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
					</tr>
					<tr>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" align="right" bgcolor="#E4E4E4">
							确认密码
						</td>
						<td height="50" colspan="2" bgcolor="#E4E4E4">
							<input name="userPwd1" type="text" id="userPwd1" size="24"
								maxlength="20">
						</td>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
					</tr>
					<tr>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" align="right" bgcolor="#E4E4E4">
							电话号码
						</td>
						<td height="50" colspan="2" bgcolor="#E4E4E4">
							<input name="userPhone" type="text" id="userPhone" size="24"
								maxlength="15">
						</td>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
					</tr>
					<tr>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" align="right" bgcolor="#E4E4E4">
							邮箱
						</td>
						<td height="50" colspan="2" bgcolor="#E4E4E4">
							<input name="userEmail" type="text" id="userEmail" size="24px"
								maxlength="30">
						</td>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
					</tr>
					<tr>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" bgcolor="#E4E4E4">
							<input type="hidden" name="userLevel" id="userLevel" value="2" />
						</td>
						<td width="41" height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td width="142" height="50" bgcolor="#E4E4E4">
							<input type="submit" name="submit" id="submit"
								onclick="return check()" value="提交">
						</td>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
					</tr>
					<tr>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" colspan="2" bgcolor="#E4E4E4">&nbsp;
							
						</td>
						<td height="50" bgcolor="#E4E4E4">&nbsp;
							
						</td>
					</tr>
				</table>
			</form>
		</div>
		<br>
	</body>
</html>

struts-user.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="user" namespace="/user" extends="struts-default">
		<action name="login" class="userAction" method="login">
			<result name="success" type="redirect">/index.jsp</result>
		</action>
		<action name="check" class="userAction" method="check">
			 <result name="check" type="redirect" >/addUser.jsp</result>
		</action>
		<action name="addUser" class="userAction" method="addUser">
			<result name="add" type="redirect">/login.jsp</result>
		</action>
		
	</package>
</struts>

check.js

function check() {

	var filter = /^\s*[.A-Za-z0-9_-]{5,15}\s*$/;

	if (!filter.test(document.addUser.userName.value)) {
	//	alert("用户名填写不正确,请重新填写!可使用的字符为(A-Z a-z 0-9 _ - .)长度不小于5个字符,不超过15个字符,注意不要使用空格。");
		checkUserNameMsg.innerHTML = "<font color='red' size='2px'><b>可使用的字符为(A-Z a-z 0-9 _ - .)长度不小于5个字符,不超过15个字符,注意不要使用空格。</b></font>"; 
		document.addUser.userName.focus();
		document.addUser.userName.select();
		return false;
	}else
	if (document.addUser.userPwd.value == "") {
		alert("请填写您的密码!");

		document.addUser.userPwd.focus();
						document.addUser.Pwd.select();

		return false;
	}
else
	if (document.addUser.userPwd1.value == "") {
		alert("请输入您的确认密码!");
		document.addUser.userPwd1.focus();
		return false;
	}
else
	var filter = /^\s*[.A-Za-z0-9_-]{5,15}\s*$/;
	if (!filter.test(document.addUser.userPwd.value)) {
		alert("密码填写不正确,请重新填写!可使用的字符为(A-Z a-z 0-9 _ - .)长度不小于5个字符,不超过15个字符,注意不要使用空格。");
		ddocument.addUser.userPwd.focus();
		document.addUser.userPwd.select();
		return false;
	}
else
	if (document.addUser.userPwd.value != document.addUser.userPwd1.value) {
		alert("两次填写的密码不一致,请重新填写!");
		document.addUser.userPwd.focus();
		document.addUser.userPwd.select();
		return false;
	}
	else
		if (document.addUser.userPhone.value == "") {
		alert("请输入您的电话!");
		document.addUser.userPhone.focus();
		document.addUser.userPhone.select();
		return false;
	}
	else
	var filter=/^1[3|4|5|8][0-9]\d{4,8}$/;
	if (!filter.test(document.addUser.userPhone.value)) {
		alert("电话号码不正确,请重新填写!");
		document.addUser.userPhone.focus();
		document.addUser.userPhone.select();
		return false;
	}
	else
	if (document.addUser.userEmail.value == "") {
		alert("请输入您的电子邮件地址!");
		document.addUser.userEmail.focus();
		document.addUser.userEmail.select();
		return false;
	}
else
	var filter = /^\s*([A-Za-z0-9_-]+(\.\w+)*@(\w+\.)+\w{2,3})\s*$/;
	if (!filter.test(document.addUser.userEmail.value)) {
		alert("邮件地址不正确,请重新填写!");
		document.addUser.userEmail.focus();
		document.addUser.userEmail.select();
		return false;
	}


	
}

抱歉!评论已关闭.