JAVAWEB項目實現驗證碼中文、英文、數字組合

驗證碼基礎

一.什麼是驗證碼及它的做用javascript

   驗證碼爲全自動區分計算機和人類的圖靈測試的縮寫,是一種區分用戶是計算機的公共全自動程序,這個問題能夠由計算機生成並評判,可是必須只有人類才能解答.能夠防止惡意破解密碼、刷票、論壇灌水、有效防止某個黑客對某一個特定註冊用戶用特定程序暴力破解方式進行不斷的登陸。html

 

二.圖文驗證碼的原理java

   在servlet中隨機生成一個指定位置的驗證碼,通常爲四位,而後把該驗證碼保存到session中.在經過Java的繪圖類以圖片的形式輸出該驗證碼。爲了增長驗證碼的安全級別,能夠輸出圖片的同時輸出干擾線,最後在用戶提交數據的時候,在服務器端將用戶提交的驗證碼和Session保存的驗證碼進行比較。程序員

 

三.驗證碼所需的技術web

    :i.由於驗證碼中的文字,數字,應爲都是可變的,故要用到隨機生成數技術。apache

       ii.若是驗證碼中包含漢字,則要用到漢字生成技術.數組

       iii.可使用Ajax技術實現局部刷新緩存

       iv.可使用圖片的縮放和旋轉技術,安全

       vi.隨機繪製干擾線(能夠是折現,直線等)服務器

       vii.若是考慮到驗證碼的安全性,可使用MD5加密.

中文、英文、數字組合驗證碼:

package randCodeImage.servlet;

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.imageio.ImageIO;
/**
 * 隨機生成英文、數字、中文驗證圖片
 * 
 * @author wkr
 * 
 */
public class PictureCheckCode extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public PictureCheckCode() {
        super();
    }

    public void destroy() {
        super.destroy(); 
    }

    public void init() throws ServletException {
        super.init();
    }
    /*該方法主要做用是得到隨機生成的顏色*/ 
    public Color getRandColor(int s,int e){
        Random random=new Random ();
        if(s>255) s=255;
        if(e>255) e=255;
        int r,g,b;
        r=s+random.nextInt(e-s);    //隨機生成RGB顏色中的r值
        g=s+random.nextInt(e-s);    //隨機生成RGB顏色中的g值
        b=s+random.nextInt(e-s);    //隨機生成RGB顏色中的b值
        return new Color(r,g,b);
    }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //設置不緩存圖片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
//        request.setCharacterEncoding("UTF-8");
//        request.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html;charset=UTF-8");
        //指定生成的響應圖片,必定不能缺乏這句話,不然錯誤.
        response.setContentType("image/jpeg");
        int width=86,height=32;        //指定生成驗證碼的寬度和高度
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);    //建立BufferedImage對象,其做用至關於一圖片
        Graphics g=image.getGraphics();        //建立Graphics對象,其做用至關於畫筆
        Graphics2D g2d=(Graphics2D)g;        //建立Grapchics2D對象
        Random random=new Random();
        Font mfont=new Font("楷體",Font.BOLD,24);    //定義字體樣式
        g.setColor(getRandColor(200,250));
        g.fillRect(0, 0, width, height);    //繪製背景
        g.setFont(mfont);                    //設置字體
        g.setColor(getRandColor(180,200));
        
        //繪製100條顏色和位置所有爲隨機產生的線條,該線條爲2f
        for(int i=0;i<100;i++){
            int x=random.nextInt(width-1);
            int y=random.nextInt(height-1);
            int x1=random.nextInt(6)+1;
            int y1=random.nextInt(12)+1;
            BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);    //定製線條樣式
            Line2D line=new Line2D.Double(x,y,x+x1,y+y1);
            g2d.setStroke(bs);
            g2d.draw(line);        //繪製直線
        }
        //輸出由英文,數字,和中文隨機組成的驗證文字,具體的組合方式根據生成隨機數肯定。
        String sRand="";
        String ctmp="";
        int itmp=0;
        //制定輸出的驗證碼爲四位
        for(int i=0;i<4;i++){
            switch(random.nextInt(3)){
                case 1:        //生成A-Z的字母
                     itmp=random.nextInt(26)+65;
                     ctmp=String.valueOf((char)itmp);
                     break;
                case 2:        //生成漢字
                     String[] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; 
                     //生成第一位區碼
                     int r1=random.nextInt(3)+11;
                     String str_r1=rBase[r1];
                     //生成第二位區碼
                     int r2;
                     if(r1==13){
                         r2=random.nextInt(7);     
                     }else{
                         r2=random.nextInt(16);
                     }
                     String str_r2=rBase[r2];
                     //生成第一位位碼
                     int r3=random.nextInt(6)+10;
                     String str_r3=rBase[r3];
                     //生成第二位位碼
                     int r4;
                     if(r3==10){
                         r4=random.nextInt(15)+1;
                     }else if(r3==15){
                         r4=random.nextInt(15);
                     }else{
                         r4=random.nextInt(16);
                     }
                     String str_r4=rBase[r4];
                     //將生成的機內碼轉換爲漢字
                     byte[] bytes=new byte[2];
                     //將生成的區碼保存到字節數組的第一個元素中
                     String str_12=str_r1+str_r2;
                     int tempLow=Integer.parseInt(str_12, 16);
                     bytes[0]=(byte) tempLow;
                     //將生成的位碼保存到字節數組的第二個元素中
                     String str_34=str_r3+str_r4;
                     int tempHigh=Integer.parseInt(str_34, 16);
                     bytes[1]=(byte)tempHigh;
                     ctmp=new String(bytes,"GB2312");
                     break;
                default:
                     itmp=random.nextInt(10)+48;
                     ctmp=String.valueOf((char)itmp);
                     break;
            }
            sRand+=ctmp;
            Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
            g.setColor(color);
            //將生成的隨機數進行隨機縮放並旋轉制定角度 PS.建議不要對文字進行縮放與旋轉,由於這樣圖片可能不正常顯示
            /*將文字旋轉制定角度*/
            Graphics2D g2d_word=(Graphics2D)g;
            AffineTransform trans=new AffineTransform();
            trans.rotate((45)*3.14/180,15*i+8,7);
            /*縮放文字*/
            float scaleSize=random.nextFloat()+0.8f;
            if(scaleSize>1f) scaleSize=1f;
            trans.scale(scaleSize, scaleSize);
            g2d_word.setTransform(trans);
            g.drawString(ctmp, 15*i+18, 14);
        }
        System.out.println("驗證碼:>>>"+sRand);
        HttpSession session=request.getSession(true);
        session.setAttribute("randCheckCode", sRand);
        g.dispose();    //釋放g所佔用的系統資源
        ImageIO.write(image,"JPEG",response.getOutputStream());    //輸出圖片
    }
}

英文、數字組合驗證碼(附加讀取配置文件):

package randCodeImage.servlet;

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

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import randCodeImage.util.ResourceUtil;

//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGEncodeParam;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 隨機生成英文、數字驗證圖片
 * 
 * @author wkr
 * 
 */
public class RandCodeImageServlet extends HttpServlet {
    private static final long serialVersionUID = -1257947018545327308L;
    private static final String SESSION_KEY_OF_RAND_CODE = "randCode"; // todo 要統一常量
    /**
     * 
     */
    private static final int count = 200;

    /**
     * 定義圖形大小
     */
    private static final int width = 105;
    /**
     * 定義圖形大小
     */
    private static final int height = 35;
    // private Font mFont = new Font("Arial Black", Font.PLAIN, 15); //設置字體
    /**
     * 干擾線的長度=1.414*lineWidth
     */
    private static final int lineWidth = 2;

    @Override
    public void doGet(final HttpServletRequest request,
            final HttpServletResponse response) throws ServletException,
            IOException {
        // 設置頁面不緩存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // response.setContentType("image/png");

        // 在內存中建立圖象
        final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 獲取圖形上下文
        final Graphics2D graphics = (Graphics2D) image.getGraphics();

        // 設定背景顏色
        graphics.setColor(Color.WHITE); // ---1
        graphics.fillRect(0, 0, width, height);
        // 設定邊框顏色
//        graphics.setColor(getRandColor(100, 200)); // ---2
        graphics.drawRect(0, 0, width - 1, height - 1);

        final Random random = new Random();
        // 隨機產生干擾線,使圖象中的認證碼不易被其它程序探測到
        for (int i = 0; i < count; i++) {
            graphics.setColor(getRandColor(150, 200)); // ---3

            final int x = random.nextInt(width - lineWidth - 1) + 1; // 保證畫在邊框以內
            final int y = random.nextInt(height - lineWidth - 1) + 1;
            final int xl = random.nextInt(lineWidth);
            final int yl = random.nextInt(lineWidth);
            graphics.drawLine(x, y, x + xl, y + yl);
        }

        // 取隨機產生的認證碼(4位數字)
        final String resultCode = exctractRandCode();
        for (int i = 0; i < resultCode.length(); i++) {
            // 將認證碼顯示到圖象中,調用函數出來的顏色相同,多是由於種子太接近,因此只能直接生成
            // graphics.setColor(new Color(20 + random.nextInt(130), 20 + random
            // .nextInt(130), 20 + random.nextInt(130)));

            // 設置字體顏色
            graphics.setColor(Color.BLACK);
            // 設置字體樣式
//            graphics.setFont(new Font("Arial Black", Font.ITALIC, 18));
            graphics.setFont(new Font("Times New Roman", Font.BOLD, 24));
            // 設置字符,字符間距,上邊距
            graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
        }

        // 將認證碼存入SESSION
        request.getSession().setAttribute(SESSION_KEY_OF_RAND_CODE, resultCode);
        // 圖象生效
        graphics.dispose();

        // 輸出圖象到頁面
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    @Override
    public void doPost(final HttpServletRequest request,
            final HttpServletResponse response) throws ServletException,
            IOException {
        doGet(request, response);
    }

    /**
     * @return 隨機碼
     */
    private String exctractRandCode() {
        final String randCodeType = ResourceUtil.getRandCodeType();
        int randCodeLength = Integer.parseInt(ResourceUtil.getRandCodeLength());
        if (randCodeType == null) {
            return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength);
        } else {
            switch (randCodeType.charAt(0)) {
            case '1':
                return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength);
            case '2':
                return RandCodeImageEnum.LOWER_CHAR.generateStr(randCodeLength);
            case '3':
                return RandCodeImageEnum.UPPER_CHAR.generateStr(randCodeLength);
            case '4':
                return RandCodeImageEnum.LETTER_CHAR.generateStr(randCodeLength);
            case '5':
                return RandCodeImageEnum.ALL_CHAR.generateStr(randCodeLength);

            default:
                return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength);
            }
        }
    }

    /**
     * 描述:
     * 
     * @param fc
     *            描述:
     * @param bc
     *            描述:
     * 
     * @return 描述:
     */
    private Color getRandColor(int fc, int bc) { // 取得給定範圍隨機顏色
        final Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }

        final int r = fc + random.nextInt(bc - fc);
        final int g = fc + random.nextInt(bc - fc);
        final int b = fc + random.nextInt(bc - fc);

        return new Color(r, g, b);
    }
}

/**
 * 驗證碼輔助類
 * 
 * @author 張國明 guomingzhang2008@gmail.com <br/>
 *         2012-2-28 下午2:15:14
 * 
 */
enum RandCodeImageEnum {
    /**
     * 混合字符串
     */
    ALL_CHAR("123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"),
    /**
     * 字符
     */
    LETTER_CHAR("abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"),
    /**
     * 小寫字母
     */
    LOWER_CHAR("abcdefghjkmnpqrstuvwxyz"),
    /**
     * 數字
     */
    NUMBER_CHAR("123456789"),
    /**
     * 大寫字符
     */
    UPPER_CHAR("ABCDEFGHJKMNPQRSTUVWXYZ");
    /**
     * 待生成的字符串
     */
    private String charStr;

    /**
     * @param charStr
     */
    private RandCodeImageEnum(final String charStr) {
        this.charStr = charStr;
    }

    /**
     * 生產隨機驗證碼
     * 
     * @param codeLength
     *            驗證碼的長度
     * @return 驗證碼
     */
    public String generateStr(final int codeLength) {
        final StringBuffer sb = new StringBuffer();
        final Random random = new Random();
        final String sourseStr = getCharStr();

        for (int i = 0; i < codeLength; i++) {
            sb.append(sourseStr.charAt(random.nextInt(sourseStr.length())));
        }

        return sb.toString();
    }

    /**
     * @return the {@link #charStr}
     */
    public String getCharStr() {
        return charStr;
    }

}

讀取配置文件工具類:

package randCodeImage.util;

import java.util.ResourceBundle;
//commons-lang-2.6.jar
import org.apache.commons.lang.StringUtils;

/** 
 * 項目參數工具類
 * @author otowa
 *
 */
public class ResourceUtil {

    //得到指定的環境變量的值env若獲取不到,由默認值pro代替
    private static final String env = StringUtils.defaultIfBlank(System.getProperty("env"), StringUtils.defaultIfBlank(System.getenv("env"), "pro"));
    
    private static final ResourceBundle sysConfig = java.util.ResourceBundle.getBundle(env+"/sysConfig");
    
    /**
     * 獲取隨機碼的長度
     *
     * @return 隨機碼的長度
     */
    public static String getRandCodeLength() {
        return sysConfig.getString("randCodeLength");
    }
    /**
     * 獲取隨機碼的類型
     *
     * @return 隨機碼的類型
     */
    public static String getRandCodeType() {
        return sysConfig.getString("randCodeType");
    }
}

sysConfig.properties配置文件(路徑:/resources/dev/sysConfig.properties):

#隨機碼的長度
randCodeLength=4
#隨機碼的類型
randCodeType=5

驗證碼jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">

    /**
     * 異步刷新驗證碼
     */
    $('#randCodeImage').click(function(){
        reloadRandCodeImage();
    });
    function reloadRandCodeImage() {
        var date = new Date();
        var img = document.getElementById("randCodeImage");
        img.src='randCodeImageServlet?a=' + date.getTime();
    }
</script>
<script language="javascript">
    /**
     * 異步刷新驗證碼
     */
    function myReload() {  
        document.getElementById("CreateCheckCode").src = document  
                .getElementById("CreateCheckCode").src  
                + "?nocache=" + new Date().getTime();  
    }  
</script>  
</head>
<body>
    <form action="">
        英文、數字驗證碼:
        <input type="text" name="code" size="4" >
        <img id="randCodeImage" alt="驗證碼" src="randCodeImageServlet">
        <a id="verifyChange" href="javascript:void(0);" onclick="reloadRandCodeImage();" >換一張</a>
    </form>
    
    <form action="page/randCodeImage/Check.jsp" method="post">
        中文、英文、數字驗證碼:
        <input name="checkCode" type="text" id="checkCode" title="驗證碼區分大小寫"  
            size="8" maxlength="4" />  
        <img src="PictureCheckCode" id="CreateCheckCode" align="middle">  
        <a href="javascript:;" onclick="myReload()"> 看不清,換一個</a>  
        <input type="submit" value="提交" />  
    </form>  
</body>
</html>

提交效驗jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page language="java" import="java.util.*"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>驗證碼校驗</title>
</head>
<body>
 <%  
         request.setCharacterEncoding("utf-8");
        String checkcode=request.getParameter("checkCode");  
         out.print("<script>alert('提交內容:"+checkcode+"');</script>");  
        if(checkcode.equals("")||checkcode==null){  
            out.print("<script>alert('請輸入驗證碼');window.location.href('index.jsp')</script>");  
        }else{  
            if(!checkcode.equalsIgnoreCase((String)session.getAttribute("randCheckCode"))){  
                out.print("<script>alert('驗證碼不正確,請從新輸入');history.back(-1);</script>");  
            }else{  
                out.print("登陸成功");  
            }  
        }  
     %>  
</body>
</html>

web.xml配置:

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

  <!-- 隨機生成驗證碼圖片 -->
  <servlet>  
    <description>輸出驗證碼</description>  
    <display-name>This is the display name of my J2EE component</display-name>  
    <servlet-name>PictureCheckCode</servlet-name>  
    <servlet-class>randCodeImage.servlet.PictureCheckCode</servlet-class>  
  </servlet>
  
  <servlet>  
    <servlet-name>RandCodeImageServlet</servlet-name>  
    <servlet-class>randCodeImage.servlet.RandCodeImageServlet</servlet-class>  
  </servlet>
  
  <!-- 隨機生成驗證碼圖片 -->
  <servlet-mapping>  
    <servlet-name>PictureCheckCode</servlet-name>  
    <url-pattern>/PictureCheckCode</url-pattern>  
  </servlet-mapping> 
<servlet-mapping> <servlet-name>RandCodeImageServlet</servlet-name> <url-pattern>/randCodeImageServlet</url-pattern> </servlet-mapping> <!-- 攔路虎 --> <display-name>sdfsdf</display-name> <welcome-file-list> <!-- 隨機生成驗證碼圖片 --> <welcome-file>page/randCodeImage/login.jsp</welcome-file> </welcome-file-list> </web-app>

頁面效果:

本文參考:程序員形同陌路

相關文章
相關標籤/搜索