利用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 οnlοad="startTime()">
? ? <div id="txt"></div>
<h2>無刷新驗證碼實現</h2>
<!-- 指定輸入框的長度為4 -->
? ? ? ? ? ? ?驗證碼:<input type="text" id="checkcode" οnkeyup="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);
}
}
總結
以上是生活随笔為你收集整理的利用Ajax实现输入完验证码之后直接判断验证码是否正确的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过生命周期管理来做热数据到冷数据的迁移
- 下一篇: 飞凌嵌入式 全志A40i系列开发板试用体