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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章