1. 程式人生 > >jsp中生成的驗證碼和存在session裡面的驗證碼不一致的處理

jsp中生成的驗證碼和存在session裡面的驗證碼不一致的處理

今天在除錯專案的時候發現,在提交表單的時候的驗證碼有問題,問題是這樣的:就是通過debug模式檢視得知:jsp頁面生成的驗證碼和表單輸入的頁面輸入的一樣,但是到後臺執行的時候,你會發現他們是不一樣的,現在上圖看看:

1.這是表單提交的時候:


2.這是後臺得到的生成的驗證碼:


3.這是後臺得到輸入的驗證碼:


這樣的問題還是頭一次出現,以前沒遇到過,經過google,baidu,最後得知是這樣的:因為載入jsp頁面比載入session快一些

那怎麼辦才能解決這個辦法呢,

又經過多次搜尋,思考,實踐,終於想出了個好辦法

1.在jsp頁面用js生成驗證碼並儲存在變數中,驗證碼作為引數傳到java(繼承了HttpServlet)類

2.根據jsp頁面中傳過來的驗證碼畫出一個有干擾線或干擾點的圖片

3.在WEB-INF/web.xml中配置 servlet

4.在jsp頁面呼叫配置好的servlet,一般是通過<img src="servlet名" id="code"/>呼叫

5.提交資料之前驗證

<form onsubmit="return validate();"……/>

區域性重新整理驗證碼:<a href="#" onclick="javascript:show();return false;">看不清,換一張!</a>-----return false;很重要啊


下面直接附上我的例子:

截圖如下:


程式碼如下:

1.JAVA類:CodeServlet.java:

package cn.gov.csrc.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
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;

public class CodeServlet extends HttpServlet {

	/**
	 * 產生驗證碼圖片
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", 0L);
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width, height, 1);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Arial", 0, 25));
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width + 100);
			int y = random.nextInt(height + 100);
			int xl = random.nextInt(10);
			int yl = random.nextInt(12);
			g.drawOval(x, y, x + xl, y + yl);
		}
		String code = request.getParameter("code");
		String sRand = code;
		for (int i = 0; i < sRand.length(); i++) {
			String rand = sRand.substring(i, i + 1);
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 14 * i + 5, 25);
		}
		g.dispose();
		javax.servlet.ServletOutputStream imageOut = response.getOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageOut);
		encoder.encode(image);
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

}


2.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">
	<display-name></display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>CodeServlet</servlet-name>
		<servlet-class>cn.gov.csrc.servlet.CodeServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CodeServlet</servlet-name>
		<url-pattern>/CodeServlet</url-pattern>
	</servlet-mapping>
</web-app>

3.index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<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 language="javascript" type="text/javascript">
var code ; //在全域性 定義驗證碼 
function createCode(){  
    code = "";  
    var codeLength = 5;//驗證碼的長度  
    //所有候選組成驗證碼的字元,可以用中文  
    var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C',
    		'D','E','F','G','H','I','J','K','L','M','N','O','P',
    		'Q','R','S','T','U','V','W','X','Y','Z','a','b','c',
    		'd','e','f','g','h','i','j','k','l','m','n','o','p',
    		'q','r','s','t','u','v','w','x','y','z');  
    for(var i=0;i<codeLength;i++){  
        var charIndex = Math.floor(Math.random()*60);  
        code +=selectChar[charIndex];  
    }  
    return code;  
}  
function validate (){  
    var inputCode = document.getElementById("vcode").value.toLowerCase();  
    if(inputCode.length <=0){  
        alert("請輸入驗證碼!");  
        return false;  
    }  
    else if(inputCode != code.toLowerCase()){  
        alert("驗證碼輸入錯誤!");  
        show();//重新整理驗證碼  
        return false;  
    }else{  
        alert("^-^ OK");  
        return true;  
    }  
}  
function show(){  
        //顯示驗證碼  
        document.getElementById("code").src="CodeServlet?code="+createCode();  
}  
window.onload = function() {
		//document.onload=show();  
        show();//頁面載入時載入驗證碼  
        //這時無論在ie還是在firefox中,js沒有載入完,頁面的東西是不會被執行的;  
    }  
</script>
</head>

<body>
	<form onsubmit="return validate();" action="" method="post">
		<h3>jsp+js+servlet實現驗證碼</h3>
		<br /> 使用者名稱:<input type="text" name="" /><br /> 請輸入驗證碼: <input
			type="text" id="vcode" style="width: 60;" maxLength="5" /> <img
			src="" id="code" /> <a href="#" mce_href="#"
			onclick="javascript:show();return false;">看不清,換一張!</a><br /> <input
			type="submit" />
	</form>
</body>
</html>


下載程式碼請訪問:http://www.zuidaima.com/share/1720368578202624.htm