Based on Ajax user name verification terms of service loading verification code generation method

  • 2020-04-01 01:55:54
  • OfStack

  Ajax (asynchronous  Javascript  And  XML) asynchronous javascript and XML.

        Is to solve the traditional web applications "sends the request - waiting for a response" the disadvantages of this pattern, (browser in after sending the request, can only wait for the server response, the user can't do other operation, the browser sends the request, will abandon the whole page, wait for the server returns a new page, that is to say, the interaction between the browser and server data volume is very big, can't do on-demand access to data) and create technology, the nature of the technology is: through a built-in browser an object (XmlHttpRequest asynchronously sends a request to the server.

        Asynchronous refers to the so-called browser did not abandon the entire page, which is not through the form submission way to send data to the server, the server in the after processing the request, return data to the XmlHttpRequest object, through the data in a javascript XmlHttpRequest can be gained. Then, using the data update page, the whole process, users don't have to wait for the server response.

Web asynchronous transmission technology. A way to communicate with the server without refreshing the entire page, in the process of waiting for the transmission of the web page, users can still interact with the system, the page can be updated without refreshing the reasonable use of the content can make users feel better and more convenient, but also do not abuse

Synchronous and asynchronous

Synchronization is a method of communication in which the sender sends the data and the receiver waits for the response before sending the next packet.    

Eg. Synchronization: submit request -> Waiting for server processing -> Return   from processing; Asynchronous means that the sender sends the data, waits for the receiver to respond, and then sends the next packet.

Eg. Asynchronous: request triggered by event -> Server processing (when the browser can still do other things) processed

XMLHttpRequest, an important object in Ajax

Important Javascript objects that raise requests to the server side can be raised through Javascript, and if multiple requests are to be raised, multiple XHR objects are required, and the result of the request is handled by predefined methods

How to create an XmlHttpRequest object  


//Gets the xmlHttpRequest object, which is implemented by the browser (the implementation is not standardized) and is created to distinguish between browsers
function getXmlHttpRequest(){          var xmlHttpRequest = null;          if ((typeof XMLHttpRequest) != 'undefined')  {                // non ie The browser                xmlHttpRequest = new XMLHttpRequest();          }else {                //ie The browser               xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp');          }          return xmlHttpRequest; }  or function createXmlHttpRequest(){        var xmlHttpRequest = null;         if(window.ActiveXObject){            xmlHttpRequest = new AvtiveXObject("Microsoft.XMLHTTP");        }else if(window.XMLHttpRequest){            xmlHttpRequest = new XMLHttpRequest();        }}





Important properties of the xmlHttpRequest object.

responseText:  Gets the text data for the server response responseXml: Gets the response from the server xml data status: Gets the status code returned by the server ( Such as 200)readyState:  To obtain xmlHttpRequest The state of communication with the server (0 , 1 , 2 , 3 , 4, Describe the different states separately ).
( uninitialized )   :  Object set up , But it hasn't been initialized yet ( Has not yet called open methods )
( Initialize the )     :  Object already created , Has not yet called send methods 
( To send data )   :   send Method called , But the current state as well http Head of the unknown 
( Data transfer ) :     Partial data accepted. 
 ( End of the response )  :   At this point, you can go through responseText/responseXml Got the data. 

How to retrieve the returned data of xmlHttpRequest

 When data is received from the server side, it must be sent in a format that the browser can understand. Server-side programming languages are generally as follows  3  Return data in various formats: 
1.Text( Also known as Html format )
2.XML
3.JSON

An example of an application implemented by an individual using Ajax

The system screenshots

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050617120517.png ">

 

System description:

System structure diagram

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050617120518.png ">

Displays the foreground page regist.jsp


<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title> User registration </title>
    <link href="css/regist.css" rel="stylesheet" type="text/css" />
      <script src="js/regist_ajax.js" type="text/javascript"></script>
  </head>

  <body onload="getRegistRuleTxt(),getCheckcode()">
   <form action="regist.do" onsubmit="return check(this);">
    <table border="1" bordercolor="gray" cellpadding="6" align="center">
        <tr>
            <td colspan="2"> 
             >> <font color="red"> User registration </font>  
             <font color="gray">[ The module specification : User name check, terms of service use Ajax Asynchronous processing , Verification code server generated ]</font>
            </td>
        </tr>
        <tr>
            <td align="right" class="left">
                 The user name :
            </td>
            <td width="580">
                <input type="text" name="username" id="username" onblur="postValidate()" class="inpt"/>   
                   <span style="color:orange" id="checkMsg" > *  User names are composed of letters, Numbers, and underscores .</span> 
            </td>
        </tr>
        <tr>
            <td align="right" class="left">
                   password :  
            </td>
            <td>
                <input type="password" name="password" id="password" class="inpt">    
                <span style="color:orange" id="pwdMsg" > *  Password length 6-8 position , For the sake of safety , Unique formats should be avoided .</span> 
            </td>
        </tr>
        <tr>
            <td align="right" class="left" class="inpt">
                 Confirm password :
            </td>
            <td>
                <input type="password" name="repassword" id="repassword" class="inpt">    
                <span style="color:orange" id="repwdMsg" > *  Confirm password , To ensure that you do not set the password hand error </span> 
            </td>
        </tr>
            <tr>
            <td align="right" class="left" class="inpt">
                 email :
            </td>
            <td>
                <input type="text" id="email" name="email" class="inpt">    
                <span style="color:orange" id="emailMsg" > *  Enter your usual email address , It is convenient for us to get in touch with you .</span>

            </td>
        </tr>

        <tr>
            <td align="right" class="left" class="inpt">
                 Verification code :
            </td>
            <td>
                <input type="text" id="checkcode" class="inpt">    
                <img id="ckcodeimage" src="imgsrc" style="border:solid #92CEDB 1px "> <!--  Verification code  -->
                <a href="javascript:;"  onclick="getCheckcode()"> Can't see , In a </a>
                <span style="color:orange" id="ckcodeMsg" > </span>
            </td>
        </tr>
        <tr>
            <td align="right" class="left">
                 The terms of service :
            </td>
            <td>
                <textarea rows="5" cols="48" style="margin-bottom:6px;margin-left:5px; color:gray" readonly="readonly" id="item" >
                </textarea>
            </td>
        </tr>

        <tr>
            <td align="right">
            </td>
            <td>
                 <input type="submit" value=" Agree to terms and register " style="width: 140px; height: 30px;"/>
            </td>
        </tr>
    </table>
   <div class="rghts" align="center">
           Copyright (c) 2013  Su Re years ( <a href="mailto:dennisit@163.com"> Contact us :dennisIT@163.com</a> )
        corporation All Rights Reserved.
   </div>
   </form>
  </body>
</html>

Asynchronous Ajax handles js

var xmlHttpRequest = getXmlHttpRequest();

        
        function getXmlHttpRequest(){
            var xmlHttpRequest = null;
            if((typeof XMLHttpRequest) != 'undefined'){
                
                xmlHttpRequest = new XMLHttpRequest();
            }else{
                
                xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp');
            }
            return xmlHttpRequest;
        }

        
        function getCheckcode(){
            var codeimage = document.getElementById("ckcodeimage");
            var url = "checkcode.do";
            codeimage.src=addTimestamp(url);
        }

        
        function getRegistRuleTxt(){
            var item = document.getElementById("item");

            var url = "rulesText.do";
            //Solve the problem of Chinese encoding when get is submitted, use encodeURI(url).true to send the request asynchronously, and addTimestamp(url) to prevent browser caching
            xmlHttpRequest.open("post",encodeURI(url),true);
            xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlHttpRequest.onreadystatechange=function(){
                if(xmlHttpRequest.readyState == 4){
                    if(xmlHttpRequest.status == 200){

                        var respText = xmlHttpRequest.responseText;
                        item.value=respText;
                    }else{
                        //System error.
                        item.value="system error";
                    }
                }else{
                        //Display check...
                        item.value="loading...";
                }
            };
            xmlHttpRequest.send(null);
        }

        
        function getValidate(){
            var username = document.getElementById("username");
            var url = "validatename.do?username=" + username.value;
            //Solve the problem of Chinese encoding when get is submitted, use encodeURI(url).true to send the request asynchronously, and addTimestamp(url) to prevent browser caching
            xmlHttpRequest.open("get",encodeURI(addTimestamp(url)),true);
            //Calls the method that checks the return status
            xmlHttpRequest.onreadystatechange=callback;
            xmlHttpRequest.send(null);
        }

        
         function postValidate(){
            var username = document.getElementById("username");
            var url = "validatename.do";
            //True means that the request is sent asynchronously. The default is true and the request can be get, post, put, delete
            xmlHttpRequest.open('post',url,true);
            xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlHttpRequest.onreadystatechange=callback;
            //If there are more than one argument, the & symlink key-value pair is used, and escape is used to solve the Chinese problem
            xmlHttpRequest.send('username=' + escape(username.value));

         }

        
        
        function callback(){
            if(xmlHttpRequest.readyState == 4){
                if(xmlHttpRequest.status == 200){
                    var respText = xmlHttpRequest.responseText;
                    innerHtmlMsg(respText);
                }else{
                    //System error.
                    innerHtmlMsg("error");
                }
            }else{
                    //Display check...
                    innerHtmlMsg("checking");
            }
        }

        
        function addTimestamp(url){
            if(url.indexOf("?")!=-1){
                //If there are parameters
                return url+"×tamp=" + new Date().valueOf();
            }else{
                //No parameters
                return url+"?timestamp=" + new Date().valueOf();
            }
        }

        
        function innerHtmlMsg(message){
            var checkMsg = document.getElementById("checkMsg");
            if(message=='exists'){
                //Username exists
                checkMsg.innerHTML= "<font color='red'>*  I'm sorry , The username already exists .</font>";
            }
            if(message=='noexists'){
                //The username can be used
                checkMsg.innerHTML= "<font color='green'>*  Congratulations to you , This user name is available .</font>";
            }
            if(message=='checking'){
                //System check
                checkMsg.innerHTML= "<font color='#0099aa'>*  The system is checking the data ...</font>";
            }
            if(message=='error'){
                //System error
                checkMsg.innerHTML= "<font color='red'> System failure , Please check the network , or <a href='#'> Contact us </a></font>";
            }
        }

Page styles regist.css

table {
        margin-top:70px;
        width:780px;
        border-collapse:collapse; 
        font-size:14px;
        border:1px solid gray; 
        font:normal 12px/1.5em " Song typeface ", Verdana, Lucida, Arial, Helvetica, sans-serif;
    } 
    .left{
        font-weight:500;
        color:#708899;
        padding-right:20px;
        background-color: #D6ECF5;
    }
    .inpt {
        border:solid #92CEDB 1px;
        width: 210px;
        height: 22px;
        margin-left: 10px;

    }
    .rghts{
        margin-top:20px;
        color:#708899;
        font-size:12px;
    }

Content in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.webapp.servlet.UserServlet</servlet-class>
    <init-param>
        <param-name>rulesfilepath</param-name>
        <param-value>/txt/item.txt</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>regist.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Captcha output utility class

package com.webapp.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
 *
 *  @version  :  1.1
 *  
 *  @author   :   Su Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
 *    
 *  @since       :  1.0         Creation time :    2013-1-20         In the afternoon 04:26:52
 *     
 *  @function :  TODO
 *
 */
public class CheckCodeImageUtil {
    private static final String[] chars = { "0", "1", "2", "3", "4", "5", "6",
        "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I" };

    private static final int SIZE = 4;        //The number of characters on the captcha
    private static final int LINES = 4;     //Interference line number
    private static final int WIDTH = 110;    //Captcha picture width
    private static final int HEIGHT = 40;    //Captcha image high
    private static final int FONT_SIZE = 21;//Font size on captcha

    
    
    public static Map<String,BufferedImage> creatCheckImage(){
        //Saves the string that produces the true value of the captcha
        StringBuffer buffer = new StringBuffer();    
        //Custom image object
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);

        Map<String,BufferedImage> map = new HashMap<String,BufferedImage>();

        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);
        Random random = new Random();

        //Draw random character
        for(int i=0; i<SIZE; i++){
            //Gets an element in the defined character set
            int rand = random.nextInt(chars.length);
            graphics.setColor(randomColor());
            graphics.setFont(new Font(null,Font.BOLD+Font.ITALIC,FONT_SIZE));
            graphics.drawString(chars[rand],(i)*WIDTH/SIZE+8 , HEIGHT/2+10);
            buffer.append(chars[rand]); //The generated string is stored in a buffer for later retrieval to be compared with the value entered by the user
        }
        //Drew interference
        for(int i=1;i<=LINES;i++){
            graphics.setColor(randomColor());
            graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH),random.nextInt(HEIGHT));
            if(i==LINES){
                graphics.setFont(new Font(null,Font.ITALIC,13));
                graphics.setColor(Color.GRAY);
                graphics.drawString(" Su ruian studio ", 5,15);

            }
        }
        map.put(buffer.toString(), image);
        return map;
    }

    
    public static Color randomColor(){
        Random random = new Random();
        Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
        return color;
    }
}

The Servlet processing class

package com.webapp.servlet;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.imageio.plugins.common.ImageUtil;
import com.webapp.util.CheckCodeImageUtil;
public class UserServlet extends HttpServlet {

    private List<String> userList;
    private String txtFilePath = null;

    
    public void init() throws ServletException {
        txtFilePath = this.getInitParameter("rulesfilepath");
        //Analog database
        userList = new Vector<String>();
        userList.add("zhangsan");
        userList.add("lisi");
        userList.add("wangwu");
        userList.add("zhaoliu");
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String uri = request.getRequestURI();
        String path = uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));

        if(path.equals("/validatename")){
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //The simulated system generates an exception test
            
            String username = request.getParameter("username");
            System.out.println("username:" + username);
            //Simulate a user data query
            boolean exist = userList.contains(username);
            if(exist){
                response.getWriter().print("exists");
            }else{
                response.getWriter().print("noexists");
            }
        }

        if(path.equals("/rulesText")){
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            String filePath = this.getServletContext().getRealPath(txtFilePath);
            File file = new File(filePath);
            StringBuffer buffer  = new StringBuffer();
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                String tmp = "";
                while((tmp = reader.readLine())!=null){
                    buffer.append(new String(tmp.getBytes("gbk"),"utf8")).append("n");
                }
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(buffer.toString().trim()!=null){
                response.getWriter().print(buffer.toString());
            }
        }

        if(path.equals("/checkcode")){
            response.setContentType("image/jpeg");
            Map<String, BufferedImage> map = CheckCodeImageUtil.creatCheckImage();
            String key =  (String)map.keySet().iterator().next();
            request.getSession().setAttribute("code",key);
            System.out.println("checkcode = " + request.getSession().getAttribute("code"));
            BufferedImage image = map.get(key);
            ImageIO.write(image, "jpeg", response.getOutputStream());

        }

    }
}


Related articles: