AJAX JSON PROTOTYPE 入门教程

作为AJAX技术而言,目前已经广泛应用在开发领域,在这里只是简单介绍ajax应用中的json框架。

 

所需要的相关文件:

 

  1. ajaxCaller.js
  2. json.js
  3. jsonrpc.js
  4. jsonrpc.jar

作为json需要这几个最基本的js文件和jar包。

 

建立工程:

 

  1. 将js相关文件放在WebRoot相关目录中;jar包放在lib中。

 

编写JSP页面:

 

 建立JSP页面

 

userRegister.jsp完整内容:

 

<%@page contentType="text/html; charset=GBK"%>
<%@page import="com.shopping.service.factory.InitFactory"%>
<%@page import="java.util.*"%>
<%@page import="com.shopping.pojo.ShoppingFindpasswordTit"%>
<%@page import="com.shopping.comm.util.ShoppingFunctionParam;"%>
<html>
 <head>
  <META http-equiv="Content-Type" content="text/html; charset=GBK">
  <title>用 户 注 册</title>
  <link href="<%=request.getContextPath()%>/css/shopping.css"
   rel="stylesheet" type="text/css" />
  <script language="javascript"
   src="<%=request.getContextPath()%>/jscript/public.js"></script>
  <script language="javascript"
   src="<%=request.getContextPath()%>/jscript/validate.js"></script>
  <script type="text/javascript"
   src="<%=request.getContextPath()%>/jscript/json.js"></script>
  <script type="text/javascript"
   src="<%=request.getContextPath()%>/jscript/ajaxcaller/ajaxCaller.js"></script>
  <script LANGUAGE="javascript">
  function check(){
   var userForm = document.userRegForm;//表单对象
   var useraccount = trim(userForm.userLoginAccount.value);//用户登录账号
   var accountflag = userForm.accountflag.value;//账号合法化标志
   if(useraccount.length == 0){//是否为空
    alert("用户登录账号不能为空,请填写登录账号!");
    userForm.userLoginAccount.focus();
    return false;
   }
   if(validateNumberAndChar(useraccount)){//是否合法
    alert("用户登录账号只能使用数字和英文字母的组合!");
    userForm.userLoginAccount.value="";
    userForm.userLoginAccount.focus();
    return false;
   }
   if(accountflag == '11'){
    alert("用户登录账号在数据库中已经存在,请更换登录账号!");
    userForm.userLoginAccount.value="";
    userForm.userLoginAccount.focus();
    return false;
   }
   var psword = trim(userForm.userLoginPassword.value);//登录密码
   if(psword.length == 0){
    alert("用户登录密码不能为空,请填写登录密码!");
    userForm.userLoginPassword.focus();
    return false;
   }
   var cmfpsword = trim(userForm.userLoginPasswordComf.value);//登录密码确认
   if(cmfpsword.length == 0){
    alert("用户登录密码确认不能为空,请填写登录确认密码!");
    userForm.userLoginPasswordComf.focus();
    return false;
   }
   if(psword != cmfpsword){//判断两次输入的密码是否相同
    alert("两次输入的密码不同,请重新输入!");
    userForm.userLoginPassword.value="";
    userForm.userLoginPasswordComf.value="";
    userForm.userLoginPassword.focus();
    return false;
   }
   if(validateNumberAndChar(psword)){//是否合法
    alert("用户登录密码只能使用数字和英文字母的组合!");
    userForm.userLoginPassword.value="";
    userForm.userLoginPasswordComf.value="";
    userForm.userLoginPassword.focus();
    return false;
   }
   var userNickname = trim(userForm.userNickname.value);//昵称
   var nicknameflag = userForm.nicknameflag.value;
   if(userNickname.length == 0){
    alert("用户昵称不能为空,请填写用户昵称!");
    userForm.userNickname.focus();
    return false;
   }
   if(nicknameflag == '11'){
    alert("用户昵称在数据库中已经存在,请更换登录账号!");
    userForm.userNickname.value="";
    userForm.userNickname.focus();
    return false;
   }
   var userSex = trim(userForm.userSex.value);//性别
   if(userSex.length == 0){
    alert("用户性别没有选择,请选择用户性别!");
    userForm.userSex.focus();
    return false;
   }
   var number = trim(userForm.imageNumber.value);//图形码
   if(number.length == 0){
    alert("图形码没有填写,请填写图形码!");
    userForm.imageNumber.focus();
    return false;
   }
   var userPro = trim(userForm.userPro.value);//密码找回问题
   if(userPro.length == 0){
    alert("密码找回问题,没有选择!");
    userForm.userPro.focus();
    return false;
   }
   var userAn = trim(userForm.userAn.value);//答案
   if(userAn.length == 0){
    alert("密码问题答案没有填写!");
    userForm.userAn.focus();
    return false;
   }
   userForm.action = "<%=request.getContextPath()%>/user/userManager.do?method=regUser";
   userForm.submit();
   return false;
  }
  function createImage(){
   document.getElementById("validateImage").innerHTML = "<img src='<%=request.getContextPath()%>/RandImage?no=<%=Math.random()%>&width=11&height=6&size=13'/>";
   document.userRegForm.imageNumber.value="";
   document.getElementById("validateImage2").innerHTML = "";
   return false;
  }
  function checkPassword(){
   var userForm = document.userRegForm;//表单对象
   var psword = trim(userForm.userLoginPassword.value);//登录密码
   var cmfpsword = trim(userForm.userLoginPasswordComf.value);//登录密码确认
   if(validateNumberAndChar(psword)){//是否合法
    document.getElementById("pasd").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>  密码包含非法字符!</font>";
    userForm.userLoginPassword.value="";
    userForm.userLoginPasswordComf.value="";
    return false;
   }
   if(psword != cmfpsword){//判断两次输入的密码是否相同
    document.getElementById("pasd").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>  两次输入的密码不同,请重新输入!</font>";
    userForm.userLoginPassword.value="";
    userForm.userLoginPasswordComf.value="";
    return false;
   }
   document.getElementById("pasd").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face.gif'/><font color=green>  密码验证通过!</font>";
   return false;
  }
  </script>
  <script LANGUAGE="javascript" type="text/javascript">
  function validate(){
   bodyVars = {
         imageNumber:$('imageNumber').value
       };
   ajaxCaller.postForPlainText("<%=request.getContextPath()%>/user/validateUserInfo.do?method=validateImageNum", bodyVars, onResponse);
   return false;
  }
  function onResponse(text){
   var dataObject = JSON.parse(text);
   $('validateImage2').innerHTML = dataObject.desc;
  }
  function validateLoginAccount(){
   var userForm = document.userRegForm;//表单对象
   var useraccount = trim(userForm.userLoginAccount.value);//用户登录账号
   if(useraccount.length == 0){//是否为空
    $('userLogin').innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>用户登录账号不能为空,请填写登录账号!</font>";
    return false;
   }
   if(validateNumberAndChar(useraccount)){//是否合法
    userForm.userLoginAccount.value="";
    document.getElementById("userLogin").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>登录账号包含非法字符!</font>";
    return false;
   }
   bodyVars = {
         userLoginAccount:$('userLoginAccount').value
       };
   ajaxCaller.postForPlainText("<%=request.getContextPath()%>/user/validateUserInfo.do?method=validateUserAcc", bodyVars, onResponseUserAccount);
   return false;
  }
  function onResponseUserAccount(text){
   var dataObject = JSON.parse(text);
   $('userLogin').innerHTML = dataObject.desc;
   if(dataObject.flag == '00'){
    document.userRegForm.accountflag.value='00';
   } else {
    document.userRegForm.accountflag.value='11';
   }
  }
  function validateNickname(){
   var userForm = document.userRegForm;//表单对象
   var userNickname = trim(userForm.userNickname.value);//用户登录账号
   if(userNickname.length == 0){//是否为空
    document.getElementById("nickname").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>  用户昵称不能为空,请填写用户昵称!</font>";
    userForm.userNickname.value="";
    return false;
   }
   bodyVars = {
         userNickname:$('userNickname').value
       };
   ajaxCaller.postForPlainText("<%=request.getContextPath()%>/user/validateUserInfo.do?method=validateUserNickName", bodyVars, onResponseUserNick);
   return false;
  }
  function onResponseUserNick(text){
   var dataObject = JSON.parse(text);
   $('nickname').innerHTML = dataObject.desc;
   if(dataObject.flag == '00'){//可是使用,唯一
    document.userRegForm.nicknameflag.value='00';
   } else {
    document.userRegForm.nicknameflag.value='11';
   }
  }
  function checkUserSex(){//验证用户性别
   var userForm = document.userRegForm;//表单对象
   var sex = userForm.userSex.value;
   if(sex.length == 0 ){//没有选择性别
    document.getElementById("sex").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>  请选择性别!</font>";
    return false;
   }
   document.getElementById("sex").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face.gif'/><font color=green>  性别已选择!</font>";
   return false;
  }
  function checkUserQQ(){//验证用户qq
   var userForm = document.userRegForm;//表单对象
   var userqq = trim(userForm.userQq.value);
   if(validateNumberThr(userqq)){//是否是数
    document.getElementById("qq").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>  用户QQ号码必须是数字组成!</font>";
    return false;
   }
   document.getElementById("qq").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face.gif'/><font color=green>  QQ号码正确!</font>";
   return false;
  }
  function checkUserMSN(){//验证用户MSN
   var userForm = document.userRegForm;//表单对象
   var userMsn = trim(userForm.userMsn.value);
   if(validateEmailSec(userMsn)){//是否是数合法
    document.getElementById("msn").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>  用户MSN号码非法!</font>";
    return false;
   }
   document.getElementById("msn").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face.gif'/><font color=green>  MSN号码正确!</font>";
   return false;
  }
  function checkUserMAIL(){//验证用户MSN
   var userForm = document.userRegForm;//表单对象
   var userMail = trim(userForm.userMail.value);
   if(validateEmailSec(userMail)){//是否是数合法
    document.getElementById("mail").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>  用户mail号码非法!</font>";
    return false;
   }
   document.getElementById("mail").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face.gif'/><font color=green>  mail号码正确!</font>";
   return false;
  }
  </script>
 </head>
 <body>
  <%
   List pwdList = (List) InitFactory.getfindPassWdProList();
  %>
  <!--一级TITLE-->
  <table width="100%" class="itsa" cellspacing="2" cellpadding="0">
   <tr>
    <td class="itsatitle">
     <h2 class="title">
      用户注册
     </h2>
    </td>
   </tr>
  </table>
  <!-- 详细内容 -->
  <form action="" name="userRegForm" method="post">
   <table width="100%" class="itsa" cellpadding="0" cellspacing="1"
    bgcolor="#AEBAC5" border="0">
    <tr class="odd">
     <td class="itsatd" width="20%">
      <font color=red> * </font> 图形码:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="text" name="imageNumber" maxlength="6"
       οnfοcus="createImage();return false;"
       οnblur="validate();return false;" />
      生成或看不清图形码,请重新点击文本框!
      <div id="validateImage">
      </div>
      <div id="validateImage2">
      </div>
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      <font color=red> * </font> 用户登录账号:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="text" name="userLoginAccount" maxlength="20"
       οnblur="validateLoginAccount();return false;" />
      用户登录账号,只能使用数字或英文字符的组合.不支持特殊字符,不区分大小写!
      <div id="userLogin">
      </div>
      <input type="hidden" name="accountflag" value="11">
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      <font color=red> * </font> 登录密码:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="password" name="userLoginPassword" maxlength="20" />
      用户登录密码只能使用数字或英文字符的组合.不支持特殊字符,不区分大小写!
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      <font color=red> * </font> 登录密码确认:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="password" name="userLoginPasswordComf" maxlength="20"
       οnblur="checkPassword();return false;" />
      <div id="pasd"></div>
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      <font color=red> * </font> 用户昵称:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="text" name="userNickname" maxlength="25"
       οnblur="validateNickname();return false;" />
      <div id="nickname"></div>
      <input type="hidden" name="nicknameflag" value="11">
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      <font color=red> * </font> 性别:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <select name="userSex" style="width: 60"
       οnchange="checkUserSex();return false;">
       <option value="">
        请选择
       </option>
       <option value="1">
        男
       </option>
       <option value="0">
        女
       </option>
      </select>
      <div id="sex"></div>
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      <font color=red> * </font> 密码提示问题:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <select name="userPro" style="width: 120" οnchange="">
       <option value="">
        请选择
       </option>
       <%
        ShoppingFindpasswordTit psw = null;
        for (int i = 0; i < pwdList.size(); i++) {
         psw = (ShoppingFindpasswordTit) pwdList.get(i);
       %>
       <option value="<%=psw.getId()%>">
        <%=psw.getProblem()%>
       </option>
       <%
        }
       %>
      </select>
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      答案:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="text" name="userAn" maxlength="20" />
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      用户QQ:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="text" name="userQq" maxlength="20"
       οnblur="checkUserQQ();return false;" />
      <div id="qq"></div>
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      用户MSN:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="text" name="userMsn" maxlength="50"
       οnblur="checkUserMSN();return false;" />
      <div id="msn"></div>
     </td>
    </tr>
    <tr class="odd">
     <td class="itsatd" width="20%">
      用户MAIL:
     </td>
     <td class="itsatd1" colspan="3" width="80%">
      <input type="text" name="userMail" maxlength="50"
       οnblur="checkUserMAIL();return false;" />
      <div id="mail"></div>
     </td>
    </tr>
    <tr>
     <td colspan="4" class="itsatd" align="center">
      <%
       HashMap map = null;
       map = (HashMap) request.getAttribute("result");
       if (map != null) {
        String head = (String) map.get("head");
        if (head.equals(ShoppingFunctionParam.MAP_FAIL_VIES)) {
         HashMap bodyMap = (HashMap) map.get("body");
         out.println(bodyMap.get("desc").toString());
        }
       }
      %>
      <font color=red> * 为必填项</font>
      <input name="B1" type="button" class="itsabutton" value="注    册"
       οnclick="check();return false;" />
      <input name="B2" type="reset" class="itsabutton" value="重新填写" />
     </td>
    </tr>
   </table>
  </form>
 </body>
</html>

 

调用的servlet的内容:

ValidateServlet.java 完整内容如下:

 

package com.shopping.web.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.shopping.comm.image.ValidateImageCode;
import com.shopping.service.user.UserInfoManagerService;

public class ValidateServlet extends HttpServlet {

 /**
  * Constructor of the object.
  */
 public ValidateServlet() {
  super();
 }

 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request
  *            the request send by the client to the server
  * @param response
  *            the response send by the server to the client
  * @throws ServletException
  *             if an error occurred
  * @throws IOException
  *             if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  service(request, response);
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to
  * post.
  *
  * @param request
  *            the request send by the client to the server
  * @param response
  *            the response send by the server to the client
  * @throws ServletException
  *             if an error occurred
  * @throws IOException
  *             if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  service(request, response);
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException
  *             if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }

 public void service(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String process = (String) request.getParameter("method");
  if (process.equals("validateImageNum")) {// 图形码验证
   validateImageNum(request, response);
  }
  if (process.equals("validateUserAcc")) {// 用户登录帐户验证
   validateUserAcc(request, response);
  }
  if (process.equals("validateUserNickName")) {// 用户登录帐户验证
   validateUserNickName(request, response);
  }
 }

 /**
  * 验证图形码
  *
  * create by zhangyong
  *
  * 2008-12-18
  *
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */

 public void validateImageNum(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String viewTxtName = (String) request.getParameter("imageNumber");
  // 判断图形码是否正确
  if (ValidateImageCode.validateSec(request, viewTxtName)) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='Green'>  图形码输入正确!</font>");
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  图形码输入错误!</font>");
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
 }

 /**
  *
  * 验证用户登录帐户是否可以使用
  *
  * create by zhangyong 2008-12-18validateUserNickName
  *
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 public void validateUserAcc(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String userLoginAccount = (String) request
    .getParameter("userLoginAccount");// 用户要注册的帐户
  ApplicationContext ctx = null;
  if (ctx == null) {
   ctx = WebApplicationContextUtils
     .getRequiredWebApplicationContext(this.getServletContext());
  }
  UserInfoManagerService service = (UserInfoManagerService) ctx
    .getBean("userManager");
  boolean flag = service.isExistUserAccount(userLoginAccount);
  if (flag) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='Green'>  恭喜您,该登录账号可以使用!</font>");
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  抱歉,您所要注册的登录账号已经被其他用户注册,请更换另外的登录账号!</font>");
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
 }

 /**
  *
  * 验证用户昵称是否可以使用
  *
  * create by zhangyong 2008-12-18
  *
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 public void validateUserNickName(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String userNickname = (String) request.getParameter("userNickname");// 用户要注册的帐户
  userNickname = new String(userNickname.getBytes("UTF-8"), "GBK");
  ApplicationContext ctx = null;
  if (ctx == null) {
   ctx = WebApplicationContextUtils
     .getRequiredWebApplicationContext(this.getServletContext());
  }
  UserInfoManagerService service = (UserInfoManagerService) ctx
    .getBean("userManager");
  boolean flag = service.isExistUserNickName(userNickname);
  if (flag) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='Green'>  恭喜您,该昵称可以使用!</font>");
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  抱歉,您所要注册的昵称已经被其他用户注册,请更换另外的昵称!</font>");
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
 }

}

 

ValidateUserInfoAction.java 完整内容:

 

 

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.shopping.web.action.user;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONObject;

import com.shopping.comm.image.ValidateImageCode;
import com.shopping.service.customer.CustomerQQManagerService;
import com.shopping.service.user.UserInfoManagerService;
import com.shopping.web.baseaction.BaseAction;
import com.shopping.web.form.UserRegForm;

/**
 * MyEclipse Struts Creation date: 12-22-2008
 *
 * XDoclet definition:
 *
 * @struts.action validate="true"
 */
public class ValidateUserInfoAction extends BaseAction {
 /**
  * 验证图形码
  *
  * create by zhangyong
  *
  * 2008-12-18
  *
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */

 public ActionForward validateImageNum(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String viewTxtName = (String) request.getParameter("imageNumber")
    .trim();
  // 判断图形码是否正确
  if (ValidateImageCode.validateSec(request, viewTxtName)) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='Green'>  图形码输入正确!</font>");
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  图形码输入错误!</font>");
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
  return null;
 }

 /**
  *
  * 验证用户登录帐户是否可以使用
  *
  * create by zhangyong 2008-12-18validateUserNickName
  *
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 public ActionForward validateUserAcc(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String userLoginAccount = (String) request.getParameter(
    "userLoginAccount").trim().toLowerCase();// 用户要注册的帐户
  UserInfoManagerService service = (UserInfoManagerService) this
    .getBean("userManager");
  boolean flag = service.isExistUserAccount(userLoginAccount);
  if (flag) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='Green'>  恭喜您,该登录账号可以使用!</font>");
   jsonObject.put("flag", "00");// 不存在
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  抱歉,您所要注册的登录账号已经被其他用户注册,请更换另外的登录账号!</font>");
   jsonObject.put("flag", "11");// 存在
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
  return null;
 }

 /**
  *
  * 验证用户昵称是否可以使用
  *
  * create by zhangyong 2008-12-18
  *
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 public ActionForward validateUserNickName(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  UserRegForm userform = (UserRegForm) form;
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String userNickname = request.getParameter("userNickname").trim();// 用户要注册的帐户
  UserInfoManagerService service = (UserInfoManagerService) this
    .getBean("userManager");
  boolean flag = service.isExistUserNickName(userNickname);
  if (flag) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='Green'>  恭喜您,该昵称可以使用!</font>");
   jsonObject.put("flag", "00");// 不存在
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  抱歉,您所要注册的昵称已经被其他用户注册,请更换另外的昵称!</font>");
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
  return null;
 }

 /**
  *
  * 判断登录账号是否存在
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws ServletException
  * @throws IOException
  */
 public ActionForward validateUserAccIsExist(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String userLoginAccount = (String) request.getParameter(
    "userLoginAccount").trim().toLowerCase();// 用户要注册的帐户
  UserInfoManagerService service = (UserInfoManagerService) this
    .getBean("userManager");
  boolean flag = service.isExistUserAccount(userLoginAccount);
  if (flag) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  sorry!您输入的账号不存在!</font>");
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='green'>  账号真实存在,请输入密码!</font>");
   jsonObject.put("flag", "11");// 存在
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
  return null;
 }

 /**
  * 判断用户登录账号是否存在
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws ServletException
  * @throws IOException
  */
 public ActionForward validateUserAccByFindUserPasd(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String userLoginAccount = (String) request.getParameter(
    "userLoginAccount").trim().toLowerCase();// 用户要注册的帐户
  UserInfoManagerService service = (UserInfoManagerService) this
    .getBean("userManager");
  // 判断用户登录账号是否存在
  boolean flag = service.isExistUserAccount(userLoginAccount);
  if (flag) {
   jsonObject.put("head", "11");
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  对不起,您输入的账号不存在!</font>");
  } else {// 如果存在,找寻密码提示问题
   String que = service.findQuestionByUserLoginAcc(userLoginAccount);
   jsonObject.put("que", que);
   jsonObject.put("head", "00");
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='green'>  输入的账号存在,可以通过密码提示问题找回密码!</font>");
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
  return null;
 }

 /**
  * 验证QQ号码是否唯一
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws ServletException
  * @throws IOException
  */
 public ActionForward validateCustomerQQ(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String customerQQ = request.getParameter("userQq").trim();
  // 获取service
  CustomerQQManagerService service = (CustomerQQManagerService) this
    .getBean("customerQQManager");
  // 判断QQ是否存在
  boolean flag = service.findCustomerQQbyQQnum(customerQQ);
  if (!flag) {
   jsonObject.put("head", "11");
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  对不起,您输入的QQ号码已存在!</font>");
  } else {// 如果存在,找寻密码提示问题
   jsonObject.put("head", "00");
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='green'>  输入的客服QQ号码可以使用!</font>");
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
  return null;
 }
}

 

 

下面详细介绍整个使用过程:

 

就以示例代码中的验证登录账号是否存在为例进行说明:

 

首先看页面的运行效果 如图:

 

当用户输入登录账号,焦点移开文本框时调用validateLoginAccount()方法,方法如下:

 

function validateLoginAccount(){
   var userForm = document.userRegForm;//表单对象
   var useraccount = trim(userForm.userLoginAccount.value);//用户登录账号
   if(useraccount.length == 0){//是否为空
    $('userLogin').innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>用户登录账号不能为空,请填写登录账号!</font>";
    return false;
   }
   if(validateNumberAndChar(useraccount)){//是否合法
    userForm.userLoginAccount.value="";
    document.getElementById("userLogin").innerHTML = "<img src='<%=request.getContextPath()%>/images/ico_face1.gif'/><font color=red>登录账号包含非法字符!</font>";
    return false;
   }
   bodyVars = {
         userLoginAccount:$('userLoginAccount').value
       };
   ajaxCaller.postForPlainText("<%=request.getContextPath()%>/user/validateUserInfo.do?method=validateUserAcc", bodyVars, onResponseUserAccount);
   return false;
  }

 

回调方法:
  function onResponseUserAccount(text){
   var dataObject = JSON.parse(text);
   $('userLogin').innerHTML = dataObject.desc;
   if(dataObject.flag == '00'){
    document.userRegForm.accountflag.value='00';
   } else {
    document.userRegForm.accountflag.value='11';
   }
  }

 

 

详细说明:

第一:首先判断是否为空(去空格后判断是否为空)

第二:提取参数:

       bodyVars = {
         userLoginAccount:$('userLoginAccount').value
       };

         通过该方法,将文本框名字为'userLoginAccount'的内容赋值给userLoginAccount

第三:制定提交传递的方法及回调函数

       ajaxCaller.postForPlainText("<%=request.getContextPath()%>/user/validateUserInfo.do?       method=validateUserAcc", bodyVars, onResponseUserAccount);

 

代码执行到这个地方就是提交给后台的action进行处理,处理正常返回后通过回调函数进行页面相应。

 

function onResponseUserAccount(text){
   var dataObject = JSON.parse(text);
   $('userLogin').innerHTML = dataObject.desc;
   if(dataObject.flag == '00'){
    document.userRegForm.accountflag.value='00';
   } else {
    document.userRegForm.accountflag.value='11';
   }
  }

回调函数:将系统返回的信息在页面进行显示。

 

action中处理的方法:

 

public ActionForward validateUserAcc(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/plain;charset=UTF-8");
  JSONObject jsonObject = new JSONObject();
  String userLoginAccount = (String) request.getParameter(
    "userLoginAccount").trim().toLowerCase();// 用户要注册的帐户
  UserInfoManagerService service = (UserInfoManagerService) this
    .getBean("userManager");
  boolean flag = service.isExistUserAccount(userLoginAccount);
  if (flag) {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face.gif'/><font color='Green'>  恭喜您,该登录账号可以使用!</font>");
   jsonObject.put("flag", "00");// 不存在
  } else {
   jsonObject
     .put(
       "desc",
       "<img src='"
         + request.getContextPath()
         + "/images/ico_face1.gif'/><font color='red'>  抱歉,您所要注册的登录账号已经被其他用户注册,请更换另外的登录账号!</font>");
   jsonObject.put("flag", "11");// 存在
  }
  byte[] bout = jsonObject.toString().getBytes("UTF-8");
  response.setIntHeader("Content-Length", bout.length);
  response.setHeader("Connection", "keep-alive");
  OutputStream out = response.getOutputStream();
  out.write(bout);
  out.flush();
  out.close();
  return null;
 }

 

详细介绍:

第一:获取页面提交过来的参数,用户登录账号。

第二:然后判断用户所输入的登录账号是否存在。

第三:把结果返回页面。

利用JsonObject对象,进行结果存放。类似HashMap的方式。用put方法进行存放。

 

页面回调函数:

 

function onResponseUserAccount(text){
   var dataObject = JSON.parse(text);
   $('userLogin').innerHTML = dataObject.desc;
   if(dataObject.flag == '00'){
    document.userRegForm.accountflag.value='00';
   } else {
    document.userRegForm.accountflag.value='11';
   }
  }

 

页面通过属性的方式来调用后台处理后的结果,dataObject.desc;

 

 

运行效果:

 

 

 系统中不存在改登录账号页面不刷新进行提示:

 

登录账号不存在

 

系统中存在该登录账号:

 

 

 登录账号存在

 

以上是整个应用的过程,希望对大家有所帮助!

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值