程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 基於Ajax用戶名驗證、辦事條目加載、驗證碼生成的完成辦法

基於Ajax用戶名驗證、辦事條目加載、驗證碼生成的完成辦法

編輯:關於JAVA

基於Ajax用戶名驗證、辦事條目加載、驗證碼生成的完成辦法。本站提示廣大學習愛好者:(基於Ajax用戶名驗證、辦事條目加載、驗證碼生成的完成辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是基於Ajax用戶名驗證、辦事條目加載、驗證碼生成的完成辦法正文


 Ajax(asynchronous javascript and xml)異步的javascript和xml.

    是為懂得決傳統的web運用中"發送要求-期待呼應"這類形式的弊病,(閱讀器在發送完要求後,只能期待辦事器的呼應,用戶不克不及做其他的操作,閱讀器發送完要求,會擯棄全部頁面,期待辦事器前往新的頁面,也就是說,閱讀器和辦事器之間交互的數據量很年夜,不克不及做到按需獲得數據)而創立的技巧,該技巧的實質是:經由過程一個閱讀器內置的一個對象(XmlHttpRequest)異步地向辦事器發送要求.

    所謂異步指的是閱讀器並沒有擯棄全部頁面,也就是否是經由過程表單提交的方法向辦事器發送數據,辦事器在處置完要求以後,前往數據給XmlHttpRequest對象,經由過程javascript可以獲得XmlHttpRequest中的數據.然後,應用該數據更新頁面,全部進程傍邊,用戶不消期待辦事器的呼應.

解釋:網頁的異步傳輸技巧.一種不消刷新全部頁面即可與辦事器通信的方法,在期待網頁的傳輸進程中,用戶仍然可以和體系停止交互,頁面不消刷新便可以更新內容公道的應用可讓用戶感到更好更便利,但也不要濫用

同步與異步

同步是指:發送方收回數據後,等吸收方發還呼應今後才發下一個數據包的通信方法。  

Eg.同步:提交要求->期待辦事器處置->處置終了前往 這個時代客戶端閱讀器不克不及干任何事異步是指:發送方收回數據後,不等吸收方發還呼應,接著發送下個數據包的通信方法 

Eg.異步:要求經由過程事宜觸發->辦事器處置(這時候閱讀器依然可以作其他工作)->處置終了

Ajax的主要對象XMLHttpRequest

主要的Javascript對象,經由過程它提起對辦事器真個要求,可以經由過程Javascript提起要求,假如要提起多個要求,須要多個XHR對象,要求的成果被事後界說好的辦法處置

若何創立XmlHttpRequest對象 

//獲得xmlHttpRequest對象,該對象由閱讀器完成(該完成並沒有尺度化),在創立該對象時,要辨別閱讀器.

function getXmlHttpRequest(){

         var xmlHttpRequest = null;

         if ((typeof XMLHttpRequest) != 'undefined')  {

               //非ie閱讀器

              xmlHttpRequest = new XMLHttpRequest();

         }else {

               //ie閱讀器

             xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp');

         }

         return xmlHttpRequest;

}

或許

function createXmlHttpRequest(){

        var xmlHttpRequest = null;

        if(window.ActiveXObject){

            xmlHttpRequest = new AvtiveXObject("Microsoft.XMLHTTP");

        }else if(window.XMLHttpRequest){

            xmlHttpRequest = new XMLHttpRequest();

        }

}





xmlHttpRequest對象的主要屬性.

responseText: 獲得辦事器呼應的文本數據

responseXml:獲得辦事器呼應的xml數據

status:獲得辦事器前往的狀況碼(好比200)

readyState: 獲得xmlHttpRequest與辦事器通信的狀況(0、1、2、3、4,分離描寫分歧的狀況).
(未初始化)   : 對象已樹立,然則還沒有初始化(還沒有挪用open辦法)
(初始化)     : 對象曾經樹立,還沒有挪用send辦法
(發送數據)   :   send辦法已挪用,然則以後的狀況和http頭未知
(數據傳送中) :    已接收部門數據。
 (呼應停止)  :  此時,可以經由過程responseText/responseXml獲得數據了。

xmlHttpRequest的前往數據獲得方法

從辦事器端吸收數據的時刻,那些數據必需以閱讀器可以或許懂得的格局來發送。辦事器真個編程說話普通以以下 3 種格局前往數據:
1.Text(又稱Html格局)
2.XML
3.JSON

小我應用Ajax完成的一個運用實例

體系截圖

 

體系解釋:

體系構造圖

展現前台頁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>用戶注冊</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">用戶注冊</font> 
             <font color="gray">[模塊解釋:用戶名檢討、辦事條目應用Ajax異步處置,驗證碼辦事端生成]</font>
            </td>
        </tr>
        <tr>
            <td align="right" class="left">
                用戶名:
            </td>
            <td width="580">
                <input type="text" name="username" id="username" onblur="postValidate()" class="inpt"/>   
                   <span id="checkMsg" > * 用戶名由字母、數字、下劃線構成.</span>
            </td>
        </tr>
        <tr>
            <td align="right" class="left">
                  暗碼: 
            </td>
            <td>
                <input type="password" name="password" id="password" class="inpt">    
                <span id="pwdMsg" > * 暗碼長度6-8位,為了平安,應防止獨一格局.</span>
            </td>
        </tr>
        <tr>
            <td align="right" class="left" class="inpt">
                確認暗碼:
            </td>
            <td>
                <input type="password" name="repassword" id="repassword" class="inpt">    
                <span id="repwdMsg" > * 確認暗碼,以包管您設置暗碼時沒有手誤</span>
            </td>
        </tr>
            <tr>
            <td align="right" class="left" class="inpt">
                郵箱:
            </td>
            <td>
                <input type="text" id="email" name="email" class="inpt">    
                <span id="emailMsg" > * 輸出您的經常使用郵箱,便利我們與您獲得接洽.</span>

            </td>
        </tr>

        <tr>
            <td align="right" class="left" class="inpt">
                驗證碼:
            </td>
            <td>
                <input type="text" id="checkcode" class="inpt">    
                <img id="ckcodeimage" src="imgsrc" > <!-- 驗證碼 -->
                <a href="javascript:;"  onclick="getCheckcode()">看不清,換一張</a>
                <span id="ckcodeMsg" > </span>
            </td>
        </tr>
        <tr>
            <td align="right" class="left">
                辦事條目:
            </td>
            <td>
                <textarea rows="5" cols="48" readonly="readonly" id="item" >
                </textarea>
            </td>
        </tr>

        <tr>
            <td align="right">
            </td>
            <td>
                 <input type="submit" value="贊成條目並注冊" />
            </td>
        </tr>
    </table>
   <div class="rghts" align="center">
           Copyright (c) 2013 蘇若年( <a href="mailto:[email protected]">接洽我們:[email protected]</a> )
        corporation All Rights Reserved.
   </div>
   </form>
  </body>
</html>

異步Ajax處置js

var xmlHttpRequest = getXmlHttpRequest();

        /*
          創立獲得xmlHttpRequest對象的辦法
         */
        function getXmlHttpRequest(){
            var xmlHttpRequest = null;
            if((typeof XMLHttpRequest) != 'undefined'){
                /*非IE閱讀器創立XMLHttpRequest對象*/
                xmlHttpRequest = new XMLHttpRequest();
            }else{
                /*IE閱讀器創立XMLHttpRequest對象*/
                xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp');
            }
            return xmlHttpRequest;
        }

        /*
         驗證碼呼應事宜
         */
        function getCheckcode(){
            var codeimage = document.getElementById("ckcodeimage");
            var url = "checkcode.do";
            codeimage.src=addTimestamp(url);
        }

        /*
           應用Ajax獲得辦事條目
         */
        function getRegistRuleTxt(){
            var item = document.getElementById("item");

            var url = "rulesText.do";
            //處理get方法提交時的中文編碼成績,應用encodeURI(url).true表現采取異步方法發送要求,addTimestamp(url)避免閱讀器緩存
            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{
                        //體系毛病.
                        item.value="system error";
                    }
                }else{
                        //顯示檢討中...
                        item.value="loading...";
                }
            };
            xmlHttpRequest.send(null);
        }

        /*
          采取get方法驗證
         */
        function getValidate(){
            var username = document.getElementById("username");
            var url = "validatename.do?username=" + username.value;
            //處理get方法提交時的中文編碼成績,應用encodeURI(url).true表現采取異步方法發送要求,addTimestamp(url)避免閱讀器緩存
            xmlHttpRequest.open("get",encodeURI(addTimestamp(url)),true);
            //挪用檢討前往狀況的辦法
            xmlHttpRequest.onreadystatechange=callback;
            xmlHttpRequest.send(null);
        }

        /*
          采取post方法驗證
         */
         function postValidate(){
            var username = document.getElementById("username");
            var url = "validatename.do";
            //true表現采取異步的辦法發送要求.默許就為true,要求方法可認為get、post、put、delete
            xmlHttpRequest.open('post',url,true);
            xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlHttpRequest.onreadystatechange=callback;
            //假如有多個參數,采取&符號鏈接鍵值對,escape用於處理中文成績
            xmlHttpRequest.send('username=' + escape(username.value));

         }

       
        /*
          監控狀況前往的辦法
         */
        function callback(){
            if(xmlHttpRequest.readyState == 4){
                if(xmlHttpRequest.status == 200){
                    var respText = xmlHttpRequest.responseText;
                    innerHtmlMsg(respText);
                }else{
                    //體系毛病.
                    innerHtmlMsg("error");
                }
            }else{
                    //顯示檢討中...
                    innerHtmlMsg("checking");
            }
        }

        /*
          增長時光戳,避免閱讀器緩存,閱讀器緩存只對get辦法緩存
         */
        function addTimestamp(url){
            if(url.indexOf("?")!=-1){
                //假如有參數
                return url+"×tamp=" + new Date().valueOf();
            }else{
                //沒有參數
                return url+"?timestamp=" + new Date().valueOf();
            }
        }

       
        function innerHtmlMsg(message){
            var checkMsg = document.getElementById("checkMsg");
            if(message=='exists'){
                //用戶名存在
                checkMsg.innerHTML= "<font color='red'>* 對不起,該用戶名曾經存在.</font>";
            }
            if(message=='noexists'){
                //用戶名可以用
                checkMsg.innerHTML= "<font color='green'>* 祝賀您,該用戶名可用.</font>";
            }
            if(message=='checking'){
                //體系檢討中
                checkMsg.innerHTML= "<font color='#0099aa'>* 體系正在停止數據檢討...</font>";
            }
            if(message=='error'){
                //體系失足
                checkMsg.innerHTML= "<font color='red'>體系毛病,請檢討收集,或許<a href='#'>接洽我們</a></font>";
            }
        }

頁面款式regist.css

table {
        margin-top:70px;
        width:780px;
        border-collapse:collapse; /* 歸並單位格之間的邊 */
        font-size:14px;
        border:1px solid gray; /*#92CEDB*/
        font:normal 12px/1.5em "宋體", 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;
    }

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>

驗證碼輸入對象類

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  : 蘇若年    <a href="mailto:[email protected]">發送郵件</a>
 *   
 *  @since      : 1.0        創立時光:    2013-1-20        下晝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;        //驗證碼上的字符個數
    private static final int LINES = 4;     //攪擾線條數
    private static final int WIDTH = 110;    //驗證碼圖片寬
    private static final int HEIGHT = 40;    //驗證碼圖片高
    private static final int FONT_SIZE = 21;//驗證碼上字體年夜小

   
    /**
     * 發生驗證碼
     *
     * @return Map<驗證碼的值,驗證碼的圖片>
     *
     */
    public static Map<String,BufferedImage> creatCheckImage(){
        //保留發生驗證碼真實值的串
        StringBuffer buffer = new StringBuffer();   
        //自界說圖片對象
        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();

        //畫隨機字符
        for(int i=0; i<SIZE; i++){
            //隨即獲得界說字符集中的一個元素
            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]); //將生成的字符串存入到buffer中,未來獲得時用於跟用戶輸出的值比擬
        }
        //畫攪擾線
        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("蘇若年任務室", 5,15);

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

    /**
     * 隨即發生色彩
     * @return
     */
    public static Color randomColor(){
        Random random = new Random();
        Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
        return color;
    }
}

Servlet處置類

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");
        //模仿數據庫
        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();
            }
            //模仿體系發生異常測試
            /*if(1==2){
                throw new ServletException("some error");
            }*/
            String username = request.getParameter("username");
            System.out.println("username:" + username);
            //模仿用戶數據查詢
            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());

        }

    }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved