最簡單的Servlet實現驗證碼

來源:互聯網
上載者:User

     現在有不少網站在使用者填寫表單時,同時要求填寫驗證碼,驗證碼的一個目的就是防範一些惡意的網站下載軟體,這些軟體能通過遍曆連結而將網站的所有網頁下載。還可以防止使用者不經過本網站的頁面而使用網站的資源。所以現在有不少網站都使用了驗證碼技術,驗證碼通常是一個在WEB伺服器上產生的隨機字串,同時以某種方式儲存起來,比如儲存到與當前的Session中,然後在使用者提交網頁時與使用者輸入的驗證比較是否一致,然而如果直接以明文的方式,還是不能防範一些功能較強的自動填寫表格的軟體。所以一般將驗證碼以圖片的形式顯示出來,同時可以將在圖片中顯示的字串進行一些處理,比如使用旋轉字元,添加背景材質等技術以增大被軟體識別的難度。下面簡要介紹一下如果實現這種驗證碼:首先實現一個servlet用來產生圖片(當然也可以用jsp實現): 

 

package untitled7;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.geom.GeneralPath;
import javax.swing.*;
import java.math.*;
public class Servlet1
        extends HttpServlet ...{
//Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException ...{
        response.setContentType(request.getContentType());
        response.setContentType("image/jpeg"); //必須設定ContentType為image/jpeg
        int length = 4; //設定預設產生4個數字
        Date d = new Date();
        long lseed = d.getTime();
        java.util.Random r = new Random(lseed); //設定隨機種子
        if (request.getParameter("length") != null) ...{
            try ...{
                length = Integer.parseInt(request.getParameter("length"));
            }
            catch (NumberFormatException e) ...{
            }
        }
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < length; i++) ...{
            str.append(r.nextInt(9)); //產生隨機數字
        }
//可以在此加入儲存驗證碼的代碼
//建立記憶體配置圖像
        BufferedImage bi = new BufferedImage(40, 16, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.clearRect(0, 0, 16, 40);
        g.setColor(Color.RED);
        g.drawString(str.toString(), 4, 12);
        try ...{
//使用JPEG編碼,輸出到response的輸出資料流
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.
                    getOutputStream());
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
            param.setQuality(1.0f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(bi);
        }
        catch (Exception ex) ...{
        }
    }
}

 

然後在需求顯示驗證碼的加入以下代碼就可以了

<img alt="" src="/WebModule1/servlet1" width="40" height="16"/>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.