本文實例為大家分享了Java隨機生成驗證碼的具體代碼,供大家參考,具體內(nèi)容如下

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.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class RandImage extends HttpServlet {/*** Constructor of the object.*/  public RandImage() {    super();  }    private int imgWidth = 0; //圖片寬度    private int imgHeight = 0; //圖片的高度    private int codeCount = 0; //圖片里面字符的個數(shù)    private int x = 0;    private int fontHeight; //字體的高度      private int codeY;     private String fontStyle; //字體樣式    //序列化ID 避免重復    private static final long serialVersionUID = 128554012633034503L;    /**    * 初始化配置參數(shù)    */public void init() throws ServletException {  // 寬度  String strWidth = "200";  // 高度  String strHeight ="80";  // 字符個數(shù)  String strCodeCount ="5";  //字體  fontStyle = "Times New Roman";// 將配置的信息轉(zhuǎn)換成數(shù)值  try {    if (strWidth != null && strWidth.length() != 0) {    imgWidth = Integer.parseInt(strWidth);    }  if (strHeight != null && strHeight.length() != 0) {  imgHeight = Integer.parseInt(strHeight);    }  if (strCodeCount != null && strCodeCount.length() != 0) {  codeCount = Integer.parseInt(strCodeCount);    }  } catch (NumberFormatException e) {    e.printStackTrace();  }      x = imgWidth / (codeCount + 1); //字符間距    fontHeight = imgHeight - 2; //字體的高度    codeY = imgHeight - 12; // 代碼高度  }    protected void processRequest(HttpServletRequest request,    HttpServletResponse response) throws ServletException, IOException {    //輸出流設(shè)置    response.setContentType("image/jpeg"); //輸出格式    response.setHeader("Pragma", "No-cache");//不緩存 重新生成    response.setHeader("Cache-Control", "no-cache");//不緩存 重新生成    response.setDateHeader("Expires", 0); //0秒失效 也是不緩存    HttpSession session = request.getSession(); //獲取session 會話    // 在內(nèi)存中創(chuàng)建圖象    BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);    // 獲取圖形上下文      Graphics2D g = image.createGraphics();    // 生成隨機類    Random random = new Random(); //隨機類    // 設(shè)定矩形的背景色    g.setColor(Color.WHITE);    //填充矩形Rect為白色    g.fillRect(0, 0, imgWidth, imgHeight);    // 設(shè)定邊框字體    g.setFont(new Font(fontStyle, Font.PLAIN + Font.ITALIC, fontHeight));    //設(shè)置邊框的顏色    g.setColor(new Color(55, 55, 12));    // 畫邊框    g.drawRect(0, 0, imgWidth - 1, imgHeight - 1);    // 隨機產(chǎn)生160條干擾線,使圖象中的認證碼不易被其它程序探測到    g.setColor(getRandColor(160, 200));    for (int i = 0; i < 160; i++) {    int x = random.nextInt(imgWidth);    int y = random.nextInt(imgHeight);    int xl = random.nextInt(12);    int yl = random.nextInt(12);    g.drawLine(x, y, x + xl, y + yl);  }      // 取隨機產(chǎn)生的認證碼(4位數(shù)字)    String sRand = "";    int red = 0, green = 0, blue = 0;    for (int i = 0; i < codeCount; i++) { //循環(huán)生成codeCount個隨機字符    //通過rgb三色隨機得到新的顏色    red = random.nextInt(255);    green = random.nextInt(255);    blue = random.nextInt(255);    //隨機得到一個0 1 2 的數(shù)字    int wordType = random.nextInt(3);//隨機得到0-2之間的3個數(shù)字    char retWord = 0;    //0 數(shù)字 1 小寫字母 2 大寫字母    switch (wordType) {  case 0:    retWord = this.getSingleNumberChar(); //得到0-9的char型數(shù)字  break;  case 1:    retWord = this.getLowerOrUpperChar(0); //得到小寫的char型字母  break;  case 2:    retWord = this.getLowerOrUpperChar(1); //得到大寫的char型字母  break;  }    sRand += String.valueOf(retWord); //將得到的隨機字符 連接起來    g.setColor(new Color(red, green, blue)); //設(shè)置一個顏色    g.drawString(String.valueOf(retWord), 2+(i) * x, codeY); //將字符寫到圖片中 對應(yīng)的位置  }    // 將認證碼存入SESSION    session.setAttribute("rand", sRand); //將得到的隨機字符存入到session回話中,驗證的時候可以調(diào)用    // 圖象生效    g.dispose(); //釋放g 對象    ServletOutputStream responseOutputStream = response.getOutputStream(); //輸出流    // 輸出圖象到頁面    ImageIO.write(image, "JPEG", responseOutputStream); //以JPEG的格式輸出    // 以下關(guān)閉輸入流!    responseOutputStream.flush();//刷新并關(guān)閉流    responseOutputStream.close();  }    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);  }    protected void doGet(HttpServletRequest request,    HttpServletResponse response) throws ServletException, IOException {    processRequest(request, response);  }    protected void doPost(HttpServletRequest request,    HttpServletResponse response) throws ServletException, IOException {    processRequest(request, response);  }    // 將整型隨機數(shù)字轉(zhuǎn)換成char返回    private char getSingleNumberChar() {    Random random = new Random();    int numberResult = random.nextInt(10);    int ret = numberResult + 48; //將字符 '0‘ 轉(zhuǎn)換成ascall碼的時候 就是48    return (char) ret;  }    //得到26個字符    private char getLowerOrUpperChar(int upper) {    Random random = new Random();    int numberResult = random.nextInt(26);    int ret = 0;    if (upper == 0) {// 小寫    ret = numberResult + 97;  } else if (upper == 1) {// 大寫    ret = numberResult + 65;    }    return (char) ret;  }}以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答