Servlet 實現隨機驗證碼

jopen 12年前發布 | 48K 次閱讀 Servlet 驗證碼(Captcha)

摘要: 網頁上的表單經常需要用到驗證碼,驗證碼是以圖片的形式顯示的,圖片由后臺Servlet生成,通過URI鏈接顯示在網頁上。

首先說明一下隨機驗證碼的流程。

 Servlet 實現隨機驗證碼


從流程圖可以看出,我們需要做一下幾步工作。


  1. 通過后臺Servlet生成隨機圖片。
  2. 創建Session會話,并通過登錄頁面進行驗證。
  3. 刷新隨機圖片超鏈接后,更換驗證碼圖片。
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.individuals.web.servlet;

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.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Barudisshu
 */
@WebServlet(name = "ImageCodeMakerServlet", urlPatterns = {"/ImageCodeMakerServlet"})
public class ImageCodeMakerServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //設置頁面不緩存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        //設置有效期
        response.setDateHeader("Expires", 0);

        //設置圖片的寬度和高度
        int width = 60, height = 20;

        //創建一個圖像對象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //獲取畫圖對象
        Graphics g = image.createGraphics();

        //創建隨機對象
        Random random = new Random();

        //用隨機顏色填充圖像背景
        g.setColor(new Color(255, 255, 255));

        //圖像形狀
        g.fillRect(0, 0, width, height);

        //設置字體
        g.setFont(new Font("Tahoma", Font.PLAIN, 20));

        //隨機數字符串
        String sRand = "";

        for (int i = 0; i < 4; i++) {
            //生成四個數字字符
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            //生成隨機顏色
            g.setColor(new Color(100 + random.nextInt(155), random.nextInt(100), 100 + random.nextInt(155)));
            //將隨機數字畫在圖像上
            g.drawString(rand, (12 + random.nextInt(2)) * i + 6, 18);
        }

        //生成干擾線
        for (int k = 0; k < 24; k++) {
            g.setColor(getRandomColor(0, 255));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(6);
            int y1 = random.nextInt(6);
            g.drawLine(x, y, x + x1, y + y1);
        }

        //生成干擾像素點
        for (int i = 0; i < 10; i++) {
            g.setColor(getRandomColor(50, 180));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.drawOval(x, y, 1, 1);
        }

        //將生成的隨機數字寫入Session會話
        request.getSession().setAttribute("randcode", sRand);

        //使圖像生效
        g.dispose();

        //輸出圖像到頁面
        ImageIO.write(image, "JPEG", response.getOutputStream());

    }

    /**
     * 產生一個隨機顏色
     *
     * @param fc 顏色分量最小值
     * @param bc 顏色分量最大值
     * @return
     */
    public Color getRandomColor(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);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

實現點擊圖片更新隨機驗證碼。需要在URL上加上Math.random(),通過不同參數的URL地址響應,否則訪問同一個URL資源將不更新。 


$('#verification').click(function () {
        $('#verification').attr('src', 'ImageCodeMakerServlet?' + Math.random());
    });


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!