利用Servlet生成動態(tài)驗證碼

UseServlet.java

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.*;

@WebServlet("/user.do")
public class UseServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //設置字符集格式為utf-8
        //req.setCharacterEncoding("UTF-8");
        
        //禁止頁面緩存
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "No-cache");
        resp.setDateHeader("Expires", 0);
        //設置響應正文的MIME類型為圖片
        resp.setContentType("image/jpeg");
        int width=60,height=20;
        /**
         * 創(chuàng)建一個位于緩存中的圖像,寬度為60,高度為20
         * */
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();//獲取用于處理圖形上下文的對象,相當于畫筆
        Random random = new Random();//創(chuàng)建生成隨機數(shù)的對象
        g.setColor(getRandomColor(200, 250));//設置圖像的背景色
        g.fillRect(0, 0, width, height);//畫一個矩形,坐標(0,0),寬度為60,高度為20
        g.setFont(new Font("Times New Roman",Font.PLAIN,18));//設定字體格式
        g.setColor(getRandomColor(160, 200));
        for (int i = 0; i < 130; i++) {//產(chǎn)生130條干擾線
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x+x1, y+y1);//在圖像的坐標x,y和坐標x+x1,y+y1之間畫干擾線
        }
        String strCode="";
        for (int i = 0; i < 4; i++) {
            String strNumber=String.valueOf(random.nextInt(10));
            strCode=strCode+strNumber;
            //設置字體的顏色
            g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));
            g.drawString(strNumber, 13*i+6, 16);//將驗證碼依次畫到圖像上,坐標x=13*i+6,y=16
        }
        req.getSession().setAttribute("Code", strCode);//把驗證碼保存到Session中
        g.dispose();//釋放此圖像的上下文以及它使用的所有系統(tǒng)資源
        ImageIO.write(image, "JPEG", resp.getOutputStream());//輸出JPEG格式的圖像
        resp.getOutputStream().flush();
        resp.getOutputStream().close();
        
        
        //req.getRequestDispatcher("index.jsp").forward(req, resp);
        
    }
    
    /**
     * 一個獲取隨機顏色的方法
     */
    public Color getRandomColor(int fc,int bc){
        Random random = new Random();
        Color randomColor = null;
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        //設置0~255之間的隨機數(shù)顏色值
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        randomColor = new Color(r,g,b);
        return randomColor;//返回具有指定紅色、綠色和藍色值的不透明的sRGB顏色
    }
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}

index.jsp

    <form action="user.do" method="post">
        <table align="center">
            <tr>
                <td>用戶名:</td>
                <td><input type="text" name="name"/></td>
            </tr>
            <tr>
                <td>密碼:</td>
                <td><input type="password" name="pwd"/></td>
            </tr>
            <tr>
                <td>性別:</td>
                <td>
                    <input type="radio" name="sex" value="男"/>男
                    <input type="radio" name="sex" value="女"/>女
                </td>
            </tr>
            <tr>
                <td>年齡:</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="text" name="email"/></td>
            </tr>
            <tr>
                <td>驗證碼:</td>
                <td><img alt="" src="<%=request.getContextPath()%>/user.do"><a href="">換一張</a></td>
            </tr>
            <tr>
                <td>輸入驗證碼:</td>
                <td><input type="text" name="code"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                <input type="submit" value="注冊"/>
                <input type="reset" value="重置"/>
                </td>
            </tr>
        </table>
    </form>
33.PNG
34.PNG
35.PNG
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容