最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

J2EE驗證碼圖片如何生成和點擊刷新驗證碼

 更新時間:2016年04月29日 12:02:01   作者:justPassBy  
這篇文章主要介紹了J2EE如何生成驗證碼圖片如何生成,如何點擊刷新驗證碼的相關(guān)方法,感興趣的小伙伴們可以參考一下

驗證碼圖片生成步驟

創(chuàng)建BufferedImage對象。
獲取BufferedImage的畫筆,即調(diào)用getGraphics()方法獲取Graphics對象。
調(diào)用Graphics對象的setColor()方法和fillRect()方法設(shè)置圖片背景顏色。
調(diào)用Graphics對象的setColor()方法和drawLine()方法設(shè)置圖片干擾線。
調(diào)用BufferedImaged對象的setRGB()方法設(shè)置圖片的噪點。
調(diào)用Graphics對象的setColor()方法、setFont()方法和drawString()方法設(shè)置圖片驗證碼。

因為驗證碼的圖片的寬度和高度要根據(jù)網(wǎng)站的風(fēng)格來確定的,所以字體的大小需要根據(jù)圖片的寬度和高度來確定,用到了小小的技巧。

package util;

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

import javax.imageio.ImageIO;

public class Verification {
  private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
  
  /**
   * 生成一個寬為width, 高為height, 驗證碼為code的圖片
   * @param width 圖片的寬
   * @param height 圖片的高
   * @param code 驗證碼字符串
   * @return 返回圖片驗證碼
   */
  public static BufferedImage getImage(int width, int height, String code){
    return getImage(width, height, code, 20);
  }
  /**
   * 生成一個寬為width, 高為height, 驗證碼為code的圖片,圖片中干擾線的條數(shù)為lineCnt
   * @param width 圖片的寬
   * @param height 圖片的高
   * @param code 驗證碼字符串
   * @param lineCnt 干擾線的條數(shù),建議為10條左右,可根據(jù)結(jié)果適當(dāng)調(diào)整
   * @return 返回圖片驗證碼
   */
  public static BufferedImage getImage(int width, int height, String code, int lineCnt){
    return createImage(width, height, code, lineCnt, 0.01);
  }
  /**
   * 生成一個寬為width, 高為height, 驗證碼為code的圖片,圖片中干擾線的條數(shù)為lineCnt
   * 噪聲比為noiseRate,即圖片中噪音像素點的百分比
   * @param width 圖片的寬
   * @param height 圖片的高
   * @param code 驗證碼字符串
   * @param lineCnt 干擾線的條數(shù),建議為10條左右,可根據(jù)結(jié)果適當(dāng)調(diào)整
   * @param noiseRate 圖片中噪音像素點占總像素的百分比
   * @return 返回圖片驗證碼
   */
  public static BufferedImage getImage(int width, int height, String code, int lineCnt, double noiseRate){
    return createImage(width, height, code, lineCnt, noiseRate);
  }
  
  /**
   * 
   * 生成一個寬為width, 高為height, 驗證碼為code的圖片,圖片中干擾線的條數(shù)為lineCnt
   * 噪聲比為noiseRate,即圖片中噪音像素點的百分比
   * @param width 圖片的寬
   * @param height 圖片的高
   * @param code 驗證碼字符串
   * @param lineCnt 干擾線的條數(shù),建議為10條左右,可根據(jù)結(jié)果適當(dāng)調(diào)整
   * @param noiseRate 圖片中噪音像素點占總像素的百分比
   * @return 返回圖片驗證碼
   */
  private static BufferedImage createImage(int width, int height, String code, int lineCnt, double noiseRate){
    int fontWidth = ((int)(width * 0.8)) / code.length();
    int fontHeight = (int)(height * 0.7);
    //為了在任意的width和height下都能生成良好的驗證碼,
    //字體的大小為fontWdith何fontHeight中的小者,
    int fontSize = Math.min(fontWidth, fontHeight);
    //drawString時要用到
    int paddingX = (int) (width * 0.1);
    int paddingY = height - (height - fontSize) / 2;
    
    //創(chuàng)建圖像
    BufferedImage buffimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    //獲得畫筆
    Graphics g = buffimg.getGraphics();
    //設(shè)置畫筆的顏色
    g.setColor(getRandColor(200, 255));
    //然后填充一個矩形,即設(shè)置背景色
    g.fillRect(0, 0, width, height);
    
    // 設(shè)置干擾線
    for (int i = 0; i < lineCnt; i++) {
        //隨機(jī)獲取干擾線的起點和終點
      int xs = (int)(Math.random() * width);
      int ys = (int)(Math.random() * height);
      int xe = (int)(Math.random() * width);
      int ye = (int)(Math.random() * height);
      g.setColor(getRandColor(1, 255));
      g.drawLine(xs, ys, xe, ye);
    }
    // 添加噪點
    int area = (int) (noiseRate * width * height);
    for(int i=0; i<area; ++i){
        int x = (int)(Math.random() * width);
        int y = (int)(Math.random() * height);
        buffimg.setRGB(x, y, (int)(Math.random() * 255));
    }
    //設(shè)置字體
    Font font = new Font("Ravie", Font.PLAIN, fontSize);
    g.setFont(font);
    
    for(int i=0; i<code.length(); ++i){
        String ch = code.substring(i, i+1);
        g.setColor(getRandColor(1, 199));
        g.drawString(ch, paddingX + fontWidth * i, paddingY);
    }
    return buffimg;
    
  }
  /**
   * 獲取隨機(jī)的顏色,r,g,b的取值在L到R之間
   * @param L 左區(qū)間
   * @param R 右區(qū)間
   * @return 返回隨機(jī)顏色值
   */
  private static Color getRandColor(int L, int R){
    if(L > 255)
      L = 255;
    if(R > 255)
      R = 255;
    if(L < 0)
      L = 0;
    if(R < 0)
      R = 0;
    int interval = R - L; 
    int r = L + (int)(Math.random() * interval);
    int g = L + (int)(Math.random() * interval);
    int b = L + (int)(Math.random() * interval);
    return new Color(r, g, b);
  }

  /**
   * 隨機(jī)生成若干個由大小寫字母和數(shù)字組成的字符串
   * @param len 隨機(jī)生成len個字符
   * @return 返回隨機(jī)生成的若干個由大小寫字母和數(shù)字組成的字符串
   */
  public static String getRandCode(int len){
    String code = "";
    for(int i=0; i<len; ++i){
      int index = (int)(Math.random() * ALPHABET.length());
      code = code + ALPHABET.charAt(index);
    }
    return code;
  }
  /**
   * 將圖片轉(zhuǎn)為byte數(shù)組
   * @param image 圖片
   * @return 返回byte數(shù)組
   * @throws IOException
   */
  public static byte[] getByteArray(BufferedImage image) throws IOException{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    return baos.toByteArray();
    //ByteArrayOutputStream 不需要close
    
  }
}

使用驗證碼圖片

在verificationCode.java這個servlet中調(diào)用上面的類生成驗證碼圖片,然后將圖片返回給客戶端。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();
    //隨機(jī)生成字符串,并寫入session
    String code = Verification.getRandCode(4);
    session.setAttribute("verification", code);
    BufferedImage image = util.Verification.getImage(100,30, code, 5);
    response.setContentType("image/png");
    
    OutputStream out = response.getOutputStream();
    out.write(util.Verification.getByteArray(image));
    out.flush();
    out.close();
    
  }
 

在index.jsp中設(shè)置驗證碼,用戶點擊驗證碼時,調(diào)用js代碼請求服務(wù)器得到新的驗證碼。因為上面的那個生成驗證碼的servlet會被瀏覽器緩存,所以js代碼中需要給該servlet一個隨機(jī)的參數(shù),這樣瀏覽器就會向服務(wù)器發(fā)請求得到新的驗證碼,而不是去緩存中讀取。

<%@page import="util.Verification"%>
<%@ 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">
    function refreshcode(){
      document.getElementById("verification").src= "/verificationCode/verificationCode?hehe="+Math.random();
    }
  </script>
</head>
<body>
  
  <form action="<%=request.getContextPath()+"/checkVerification" %>" method="post">
    驗證碼:<input type="text" name="submitVerification">
    <img id="verification" alt="" title="看不清點擊刷新驗證碼" src="<%=request.getContextPath()+"/verificationCode" %>"
    onclick="refreshcode()"><br>
    <input type="submit" name="submit" value="提交">
  </form>
  
</body>
</html>

最后是在checkVerification.java這個servlet中判斷用戶輸入的驗證碼是否正確,為了方便用戶,驗證碼一般都設(shè)置成大小寫不敏感,所以要先轉(zhuǎn)化為小寫字母再比對。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  HttpSession session = request.getSession();
  String verification = (String)session.getAttribute("verification");
  String submitVerification = request.getParameter("submitVerification");
  PrintWriter out = response.getWriter();
  if(verification!=null && submitVerification!=null){
   if(verification.toLowerCase().equals(submitVerification.toLowerCase())){
    out.println("yes!!!");
   }
   else{
    out.println("no!!!");
   }
   
  }
  else{
   out.println("no!!!");
  }
  session.removeAttribute("verification");//防止用戶重復(fù)提交表單

 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  doGet(request, response);
 }

最后運行的效果圖如下

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。

相關(guān)文章

  • Spring事務(wù)失效場景原理及解決方案

    Spring事務(wù)失效場景原理及解決方案

    這篇文章主要介紹了Spring事務(wù)失效場景原理及解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-09-09
  • Mybatis批量插入和批量更新失敗問題

    Mybatis批量插入和批量更新失敗問題

    這篇文章主要介紹了Mybatis批量插入和批量更新失敗問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 解決使用this.getClass().getResource()獲取文件時遇到的坑

    解決使用this.getClass().getResource()獲取文件時遇到的坑

    這篇文章主要介紹了解決使用this.getClass().getResource()獲取文件時遇到的坑問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • java中this的n種使用方法

    java中this的n種使用方法

    this可能是幾乎所有有一點面向?qū)ο笏枷氲恼Z言都會引用到的變量,this有多少種用法。下面小編給大家?guī)砹薺ava中this的n種使用方法,感興趣的朋友一起看看吧
    2018-08-08
  • 詳解Java消息隊列-Spring整合ActiveMq

    詳解Java消息隊列-Spring整合ActiveMq

    本篇文章主要介紹了詳解Java消息隊列-Spring整合ActiveMq ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-02-02
  • Java Web 登錄頁面的實現(xiàn)代碼實例

    Java Web 登錄頁面的實現(xiàn)代碼實例

    這篇文章主要介紹了Java Web 登錄頁面的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • 基于JavaMail實現(xiàn)簡單郵件發(fā)送

    基于JavaMail實現(xiàn)簡單郵件發(fā)送

    這篇文章主要為大家詳細(xì)介紹了基于JavaMail實現(xiàn)簡單郵件發(fā)送,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • win10系統(tǒng)64位jdk1.8的下載與安裝教程圖解

    win10系統(tǒng)64位jdk1.8的下載與安裝教程圖解

    這篇文章主要介紹了win10系統(tǒng)64位jdk1.8的下載與安裝教程圖解,本文給大家介紹的非常詳細(xì),對大家的工作或?qū)W習(xí)具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • zookeeper watch機(jī)制的理解

    zookeeper watch機(jī)制的理解

    這篇文章主要介紹了zookeeper watch機(jī)制的相關(guān)內(nèi)容,內(nèi)容比較詳細(xì),需要的朋友可以參考下。
    2017-09-09
  • 如何使用Java在excel單元格中設(shè)置超鏈接

    如何使用Java在excel單元格中設(shè)置超鏈接

    這篇文章主要介紹了如何使用Java在excel單元格中設(shè)置超鏈接,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-11-11

最新評論

穆棱市| 沐川县| 汝州市| 高平市| 雅江县| 长顺县| 石嘴山市| 泽州县| 三都| 白河县| 简阳市| 桂阳县| 固镇县| 临汾市| 丹巴县| 栾城县| 南部县| 冀州市| 宾阳县| 大兴区| 修武县| 资讯 | 遵化市| 福贡县| 阿拉善右旗| 昭通市| 秀山| 龙江县| 当涂县| 田阳县| 贡嘎县| 饶河县| 土默特左旗| 塔城市| 遂宁市| 陕西省| 玉溪市| 仲巴县| 太保市| 千阳县| 邹城市|