1. 程式人生 > >利用Ajax實現輸入完驗證碼之後直接判斷驗證碼是否正確

利用Ajax實現輸入完驗證碼之後直接判斷驗證碼是否正確

生成驗證碼的Servlet:

package com.muke;
//生成驗證碼;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


public CheckCodeServlet() {
super();
}


protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
doPost(request, response);
}


protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
try {
createCheckCodeImage(68, 22, new Color(150, 180, 195), request,response);
} catch (IOException e) {
e.printStackTrace();
System.out.println("驗證碼生成失敗");
}
}
// 建立驗證碼圖片
private void createCheckCodeImage(int width, int height, Color bgColor,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
String codeStr = createCheckCode(request,g);
addRandomLine(g, width, height, 5);
ImageIO.write(bi, "JPG", response.getOutputStream());
//request.getSession().setAttribute("piccode", codeStr);
createCheckCodeSession(request, codeStr);
 }
// 新增干擾線
private void addRandomLine(Graphics g, int width, int height, int numbers) {
Random r = new Random();//生成隨機數,此處生成隨機線條;
for (int i = 0; i < numbers; i++) {
int x1 = r.nextInt(width);
int x2 = r.nextInt(width);
int y1 = r.nextInt(height);
int y2 = r.nextInt(height);
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.drawLine(x1, y1, x2, y2);
}
}
// 隨機建立驗證碼
private String createCheckCode(HttpServletRequest request,Graphics g) {
char[] code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123466789".toCharArray();
Random r = new Random();
int len = code.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int index = r.nextInt(len);
// 記得在向圖片新增驗證碼前設定驗證碼的顏色,否則可能會出現有一個驗證碼看不見的情況
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
g.drawString(code[index] + "", (i * 15) + 3, 18);
sb.append(code[index]);
}
System.out.println(sb);
return sb.toString();
}
// 把驗證碼中的資料儲存在session,以便來驗證登入
private void createCheckCodeSession(HttpServletRequest request, String str) {
request.getSession().setAttribute("piccode", str);
String piccode = (String) request.getSession().getAttribute("piccode");
System.out.println(piccode);
}
}

JSP頁面:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!doctype html>
<html>
  <head>
    <base href="<%=basePath%>">
    <title>無重新整理驗證碼驗證</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">
<script type="text/javascript" src="/checkcode/js/yanzhengma.js"
charset="utf-8"></script>
<script type="text/javascript">
function startTime()
{
var today=new Date()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
m=checkTime(m)
s=checkTime(s)
document.getElementById('txt').innerHTML=h+":"+m+":"+s
t=setTimeout('startTime()',500)
}


function checkTime(i)
{
if (i<10) 
  {i="0" + i}
  return i
}
</script>
<!-- 當輸入框輸入了四個字元後,就自動進行驗證碼的驗證操作 -->
<script>
function myFunction(id) {
var l=document.getElementById(id).value.length
if(l==4){
var x = document.getElementById(id).value;
   checkYanzhengma();
}
}
</script>
<script type="text/javascript">
function reloadCode(){
var time = new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath()%>/CheckCodeServlet?d="+time;
}
</script>
  </head>
 <body onload="startTime()">
    <div id="txt"></div>
<h2>無重新整理驗證碼實現</h2>
<!-- 指定輸入框的長度為4 -->
             驗證碼:<input type="text" id="checkcode" onkeyup="myFunction(this.id)" maxlength="4"/>
    <img alt="驗證碼" id="imagecode" src="<%=request.getContextPath() %>/CheckCodeServlet"/>
    <a href="javascript: reloadCode();">看不清楚</a><br>
    <span id="tip" style="display: none; color: red"></span>
  </body>

</html>

JavaScript程式碼:

//通過Ajax實現無重新整理驗證驗證碼;
var $ = function(id) {
  return document.getElementById(id);
}
// 得到 XMLHttpRequest 物件
var getXMLHttpRequest = function() {
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest();
  } catch (e) {
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e2) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e3) {
        window.alert("Sorry,your browser does not support Ajax!");
      }
    }
  }
  return xmlHttp;
}
var xmlHttp = "";
// 檢測 username
var checkYanzhengma = function() {
  // 得到 XMLHttpRequest
  xmlHttp = getXMLHttpRequest();
  if (xmlHttp) {
    // open document.URL +
    xmlHttp.open("post", "CheckYanzhengma", true);//url對應CheckYanzhengma.java檔案,true 非同步,false 同步
    // window.alert(document.URL + "CheckYanzhengma");
    // 設定 Content-type
    xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//傳送一個HTTP協議的標頭檔案
    // 設定回撥函式
    xmlHttp.onreadystatechange = statechange;
    // send
    var sendData = "checkcode=" + $("checkcode").value;
    xmlHttp.send(sendData);
  }
}
// ajax回撥函式
var statechange = function() {
  // 0: 請求未初始化
  // 1: 伺服器連線已建立
  // 2: 請求已接收
  // 3: 請求處理中
  // 4: 請求已完成,且響應已就緒
  if (xmlHttp.readyState == "4") {
    // 200: "OK"
    // 404: 未找到頁面
    if (xmlHttp.status == "200") {  //當 readyState 等於 4 且狀態為 200 時,表示響應已就緒:
      var isOK = xmlHttp.responseText;
      if ("t" == isOK) {
        $("tip").innerHTML = "驗證碼正確!";
      } else if ("f" == isOK) {
        $("tip").innerHTML = "驗證碼錯誤,請重新輸入!";
        //$("checkcode").value = "";
      }
      $("tip").style.display="inline-block";//將物件呈現為inline物件,但是物件的內容作為block物件呈現。之後的內聯物件會被排列在同一行內。比如我們可以給一個link(a元素)inline-block屬性值,使其既具有block的寬度高度特性又具有inline的同行特性。
    }
  }
}

驗證驗證碼的Servlet:

package com.ajax;


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


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


@WebServlet("/CheckYanzhengma")
public class CheckYanzhengma extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    public CheckYanzhengma() {
        super();
    }


protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
String piccode = (String) request.getSession().getAttribute("piccode");
String checkcode = request.getParameter("checkcode");
checkcode = checkcode.toUpperCase();//toUpperCase() 方法用於把字串轉換為大寫,即使用者輸入的小寫字母轉換為大寫字母后再做判斷;
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
if(checkcode.equals(piccode)){
out.print("t");
}else{
out.print("f");
//piccode=null;
}
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
   this.doGet(request,response);
}


}