java生成驗證碼

個人認爲效果還可以,並且比較簡單生成的驗證碼的例子!!!!

java代碼:

package com.trs.nfdaily.imgcode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;


public class MakeCertPic
{
  private char[] mapTable = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };//驗證碼內容


  public String getCertPic(int width, int height, OutputStream os)
  {
    if (width <= 0)
      width = 60;
    if (height <= 0)
      height = 20;
    BufferedImage image = new BufferedImage(width, height, 
      1);


    Graphics g = image.getGraphics();


    g.setColor(new Color(14474460));
    g.fillRect(0, 0, width, height);


    g.setColor(Color.black);
    g.drawRect(0, 0, width - 1, height - 1);


    String strEnsure = "";


    for (int i = 0; i < 4; i++) {
      strEnsure = strEnsure + this.mapTable[((int)(this.mapTable.length * java.lang.Math.random()))];
    }


    g.setColor(Color.black);
    g.setFont(new Font("Atlantic Inline", 0, 18));
    String str = strEnsure.substring(0, 1);
    g.drawString(str, 8, 17);
    str = strEnsure.substring(1, 2);
    g.drawString(str, 20, 15);
    str = strEnsure.substring(2, 3);
    g.drawString(str, 35, 18);
    str = strEnsure.substring(3, 4);
    g.drawString(str, 45, 15);


    Random rand = new Random();
    for (int i = 0; i < 10; i++) {
      int x = rand.nextInt(width);
      int y = rand.nextInt(height);
      g.drawOval(x, y, 1, 1);
    }


    g.dispose();
    try
    {
      ImageIO.write(image, "JPEG", os);
    } catch (IOException e) {
      return "";
    }
    return strEnsure;
  }

}


jsp代碼

imgCode.jsp

<%@page contentType="image/jpeg" %>
<jsp:useBean id="image" scope="page" class="com.trs.nfdaily.imgcode.MakeCertPic" />
<%
String str=image.getCertPic(0,0,response.getOutputStream());
 // 將認證碼存入SESSION
session.setAttribute("imgcode", str);
  out.clear();
 out = pageContext.pushBody();
%>


login.jsp

//驗證碼
    function changeCode(){
document.getElementById("rc").src="imgCode.jsp?time="+new Date().getTime(); 
}


 </tr>
    <tr><td align="right" valign="top">驗證碼:</td><td><input name="imgcode" id="imgCode" width="15px" height="50px" class="write" ></td></tr>
  <tr><td><div><img src="imgCode.jsp" id="rc"  name="image" />&nbsp;&nbsp;</td><td><a href="javaScript:changeCode()">看不清?點擊更換</a></div></td></tr>

發佈了21 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章