Servlet登錄驗證碼

jopen 12年前發布 | 29K 次閱讀 Servlet Java開發

本文是收集加整理
Servlet代碼:

package artshell;

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

/**
 * @see http://ewf-momo.iteye.com/blog/1678955
 */
@WebServlet("/ConfirmCode")
public class LoginConfirmCode extends HttpServlet {
    private static final long serialVersionUID = -7581060780017197844L;
    public static Random random = new Random();
    // 驗證碼字符集
    public static final char[] CHARS = {
        '1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f',
        'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
        'w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L',
        'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
    };
    public LoginConfirmCode() {
        super();
    }

    // 從字符集中得到隨機字符串
    public static String getRandomChars() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }

    // 得到隨機顏色
    public static Color getRandomColor() {
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }

    // 得到隨機顏色的反色
    public static Color getReverseColor(Color c) {
        return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
    }

    public void init(ServletConfig config) throws ServletException {
        super.init();
    }

    public void destroy() {
        super.destroy();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 設置響應類型
        response.setContentType("image/jpeg");
        // 讓瀏覽器不保存緩存,目的是防止刷新驗證碼時得到與先前相同驗證碼
        response.setHeader("Cache-Control", "no-cache");
        // 得到隨機字符串
        String randomChars = getRandomChars();
        // 把隨機數存到Session里面,便于等下比較
        HttpSession session = request.getSession();
        session.setAttribute("ConfirmCode", randomChars);
        // 得到隨機顏色
        Color color = getRandomColor();
        // 得到隨機顏色的反色
        Color reverse = getReverseColor(color);
        // 在內存中創建圖像,width=80,height=20
        BufferedImage image = new BufferedImage(85, 30, BufferedImage.TYPE_INT_RGB);
        // 得到圖像繪制類對象
        Graphics g = image.getGraphics();
        // 設置驗證碼的字體種類、樣式、字號
        g.setFont(new Font(Font.SANS_SERIF, Font.LAYOUT_RIGHT_TO_LEFT, 16));
        // 設置字體顏色
        g.setColor(color);
        // 填充一個矩形
        g.fillRect(0, 0, 90, 30);
        // 設置矩形的填充顏色
        g.setColor(reverse);
        // 繪制字符串
        g.drawString(randomChars, 10, 20);
        // 隨機產生驗證碼上的干擾線
        for (int i = 0, n = random.nextInt(100); i < n; i++) {
            g.drawRect(random.nextInt(100), random.nextInt(30), random.nextInt(2), random.nextInt(2));
        }
        // 關閉Graphics 對象,釋放此圖形的上下文以及它使用的所有系統資源
        g.dispose();

        // 得到字節輸出流對象
        ServletOutputStream out = response.getOutputStream();
        // 將圖像輸出到頁面
        ImageIO.write(image, "JPEG", out);
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}

前端頁面代碼:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base href="<%=basePath%>>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
<script type="text/javascript">
    function changeValidateCode(obj) {
        /*每次請求用當前時間作為參數,防止瀏覽器使用緩存數據,如果不采取這種方法,也可以把頁面設置為不緩存*/
        var timeNow = new Date().getTime();
        obj.src = "ConfirmCode?time=" + timeNow;
    }
</script>
</head>
<body>
<form action="CheckLogin" method="post">
<table border="1">
    <tr>
        <td>用戶名:</td>
        <td><input type="text" name="username" /></td>
    </tr>
    <tr>
        <td>密碼:</td>
        <td><input type="password" name="userpwd" /></td>
    </tr>
    <tr>
        <td>驗證碼:</td>
        <td><input type="text" name="code" size="8"/><img src="ConfirmCode" onclick="changeValidateCode(this)" alt="點擊圖像刷新驗證碼" /></td>
    </tr>
    <tr>
        <td><input type="submit" value="提交" /></td>
        <td><input type="reset" value="重置"/></td>
    </tr>
</table>
</form>
</body>
</html>

原文地址:http://ewf-momo.iteye.com/blog/1678955

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