一次性驗證碼

為方便查看,只寫關鍵部分代碼

1.在jsp頁面中 ,添加鏈接servlet


<tr>
<td style="text-align:right;width:20%;"> </td>
<td colspan="2" style="width:50%">
<!--k1 圖片由CheckImgServlet生成 -->
<img  src="${pageContext.request.contextPath}/servlet/CheckImgServlet" width="180"
height="30" class="textinput"  style="height:30px;" id="img" />  
<!--k1 點一下文字鏈接切換激活圖片   -->
<a href="javascript:void(0);" onclick="changeImage()">看不清換一張</a>
</td>
</tr>

2.前端JS腳本執行切換圖片

<script type="text/javascript">
//前端點擊切換圖片,跳轉到CheckImgServlet并把當前時間傳過去
function changeImage() 
{
     document.getElementById("img").src ="${pageContext.request.contextPath}/servlet/CheckImgServlet?time="+ new Date().getTime();
}
</script>

3.驗證碼生成工具,將驗證碼文件new_words.txt放入/WEB-INF/目錄下,隨機讀取保存到session中

public class CheckImgServlet extends HttpServlet
{

    // 集合中保存所有成語
    private List<String> words = new ArrayList<String>();

    @Override
    public void init() throws ServletException
    {
// web工程中讀取 文件,必須使用絕對磁盤路徑
        String path = getServletContext().getRealPath("/WEB-INF/new_words.txt");
//創建一個使用默認大小輸入緩沖區的BufferedReader
            BufferedReader reader = new BufferedReader(newInputStreamReader(new FileInputStream(path), "UTF-8"));
            String line;
            //讀取一個文本行,如果已到達流末尾,則返回 null 
            while ((line = reader.readLine()) != null)
            {
                //每一行放進集合
                words.add(line);
            }
            reader.close();
    }

    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

        // 禁止緩存3種方式
        // response.setHeader("Cache-Control", "no-cache");
        // response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);

        int width = 120;
        int height = 30;

        // 步驟一 繪制一張內存中圖片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 步驟二 圖片繪制背景顏色 ---通過繪圖對象
        Graphics graphics = bufferedImage.getGraphics();// 得到畫圖對象 --- 畫筆
        // 繪制任何圖形之前 都必須指定一個顏色
        graphics.setColor(getRandColor(200, 250));
        graphics.fillRect(0, 0, width, height);

        // 步驟三 繪制邊框
        graphics.setColor(Color.WHITE);
        graphics.drawRect(0, 0, width - 1, height - 1);

        // 步驟四 四個隨機數字
        Graphics2D graphics2d = (Graphics2D) graphics;
        // 設置輸出字體
        graphics2d.setFont(new Font("宋體", Font.BOLD, 18));

        Random random = new Random();// 生成隨機數
        int index = random.nextInt(words.size());
        String word = words.get(index);// 獲得成語

        System.out.println("session word=" + word);

        // 定義x坐標
        int x = 10;
        for (int i = 0; i < word.length(); i++)
        {
            // 隨機顏色
            graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
                    .nextInt(110), 20 + random.nextInt(110)));
            // 旋轉 -30 --- 30度
            int jiaodu = random.nextInt(60) - 30;
            // 換算弧度
            double theta = jiaodu * Math.PI / 180;

            // 獲得字母數字
            char c = word.charAt(i);

            // 將c 輸出到圖片
            graphics2d.rotate(theta, x, 20);
            graphics2d.drawString(String.valueOf(c), x, 20);
            graphics2d.rotate(-theta, x, 20);
            x += 30;
        }

//k4 將驗證碼內容保存session
        request.getSession().setAttribute("checkcode_session", word);

        // 步驟五 繪制干擾線
        graphics.setColor(getRandColor(160, 200));
        int x1;
        int x2;
        int y1;
        int y2;
        for (int i = 0; i < 30; i++)
        {
            x1 = random.nextInt(width);
            x2 = random.nextInt(12);
            y1 = random.nextInt(height);
            y2 = random.nextInt(12);
            graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
        }

        // 將上面圖片輸出到瀏覽器 ImageIO
        graphics.dispose();// 釋放資源
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

    }

    private 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);
    }

}

4.用戶提交數據到servlet處理

public class UserRegisterServlet extends HttpServlet
{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

//用戶輸入的驗證碼
        String ckcode = (String) request.getParameter("ckcode");

//session里面保存的驗證碼
        String checkcode_session = (String) request.getSession().getAttribute("checkcode_session");

        if (checkcode_session != null)
        {
            if (checkcode_session.equals(ckcode))
            {//驗證碼符合條件
                    //用dbutils工具封裝數據
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    User user = new User();
                    BeanUtils.populate(user, parameterMap);

                    System.out.println(user);
// 插入用戶數據,跳轉到登陸成功界面
                    UserService service = new UserServiceImpl();
                    service.register(user);

                    request.getRequestDispatcher("/registersuccess.jsp").forward(request, response);
            }
            else
            {
                //驗證碼不正確
            request.setAttribute("ckcode_msg", "驗證碼有誤!");
            request.getRequestDispatcher("/register.jsp").forward(request,response);

            }

        }

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

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,837評論 0 11
  • 這部分主要是與Java Web和Web Service相關的面試題。 96、闡述Servlet和CGI的區別? 答...
    雜貨鋪老板閱讀 1,425評論 0 10
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,970評論 6 342
  • 從三月份找實習到現在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發崗...
    時芥藍閱讀 42,372評論 11 349