用java代碼 產生驗證碼的一個樣本類

來源:互聯網
上載者:User

在jsp裡這樣調用

 <table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin:0 auto;">
          <tr>
          <td width="20"><html:text property="validateCode" size="8" /></td>

         <td>&nbsp;</td><td align="left" valign="top"><div id="validateCodeImage" valign="top"></div>

        <script type="text/javascript">updateValidateCode(70, 25)</script><

        /td>
        </tr>
 </table>

js裡指令碼

function updateValidateCode(width, height) {
  document.getElementById('validateCodeImage').innerHTML = '<img id="validateCodeImg"  onclick="updateValidateCode(' + width + ', '+ height + ')" width="' + width + '" height="' + height + '" src="<%= contextPath %>/validatecode.do" style="cursor:hand" alt="如果看不清驗證碼,請點圖片重新整理" />';
}

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

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

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * MyEclipse Struts Creation date: 05-31-2007
 *
 * XDoclet definition:
 *
 * @struts.action validate="true"
 */
public class ValidateCodeAction extends Action {
    /*
     * Generated Methods
     */

    /**
     * Method execute
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        // 設定圖片的長寬
        int width = StringUtils.isNotBlank(request.getParameter("width")) ? Integer
                .parseInt(request.getParameter("width"))
                : 0;
        int height = StringUtils.isNotBlank(request.getParameter("height")) ? Integer
                .parseInt(request.getParameter("height"))
                : 0;
        if (width < 70 || width > 140) {
            width = 70;
        }
        if (height < 25 || height > 50) {
            height = 25;
        }

        // 建立記憶體配置圖像
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 擷取圖形上下文
        Graphics g = image.createGraphics();

        // 設定映像背景色(因為是做背景,所以偏淡)
        g.setColor(getRandColor(180, 250));
        g.fillRect(0, 0, width, height);
        // 設定字型
        g.setFont(new Font("Arial", Font.BOLD, 19));

        // 設定預設產生4個驗證碼
        int length = 4;
        // 設定隨機種子
        java.util.Random rand = new Random();

        // 設定備選驗證碼:包括"a-z"和數字"0-9",其中去掉了一些容易混淆的字元
        String base = "abcdefghijkmnqrstuvwxyz23456789";
        int size = base.length();
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int start = rand.nextInt(size);
            String tmpStr = base.substring(start, start + 1);

            str.append(tmpStr);
            // 產生隨機顏色(因為是做前景,所以偏深)
            g.setColor(getRandColor(10, 150));

            // 將此字畫到圖片上
            // g.drawString(str.toString(), 4, 17);
            g.drawString(tmpStr, 13 * i + 6 + rand.nextInt(5), 14 + rand
                    .nextInt(6));
            // 隨機畫點
            for (int j = 0; j < 20; j++) {
                int x = rand.nextInt(width);
                int y = rand.nextInt(height);
                g.drawOval(x, y, 0, 0);
            }
            /*
            // 隨機畫線
            for (int j = 0; j < 2; j++) {
                int x = rand.nextInt(width);
                int y = rand.nextInt(height);
                int x1 = rand.nextInt(12);
                int y1 = rand.nextInt(12);
                g.drawLine(x, y, x + x1, y + y1);
            }
            */
        }

        // 將認證碼存入session
        request.getSession().setAttribute("validateCode", str.toString());

        // 圖象生效
        g.dispose();

        // 設定頁面不緩衝
        response.setDateHeader("Expires", -1);
        response.setHeader("Cache-Control",
                "no-store, private, post-check=0, pre-check=0, max-age=0");
        response.setHeader("Pragma", "no-cache");

        // 輸出圖象到頁面
        try {
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    // 給定範圍獲得一個隨機顏色
    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);
    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.