1. 程式人生 > >登入介面中的驗證碼的使用

登入介面中的驗證碼的使用

登入介面中驗證碼的使用

  1. 第一次頁面載入時,就顯示出驗證碼的圖片,在HTML中設定好圖片的src(訪問哪一個action)
  2. 點選圖片時會重新整理驗證碼,重新整理時要定義一個函式,重新發送獲取驗證碼的請求(加上時間挫,這樣瀏覽器才會重新發送請求)
  3. 點選後邊的“換一張”時,原理和2中相同(所用的方法也相同)

HTML中程式碼

<li>
  <label for="captcha">驗證碼:</label>
  <span class="bg_text small">
    <input type="text" id="captcha"
name="captcha" maxLength="7" vld="{required:true}" />
</span> <img id="captchaImage" src="${path }/user/getImage.do" onclick="changeImage()" class="code" alt="換一張" /><a href="javascript:void(0);" onclick="changeImage()" title="換一張">換一張</a> </li>

js中程式碼

//當再次點選 時 會 重新發送請求 
function changeImage(){ var path = "${path}/user/getImage.do?date="+new Date(); $("#captchaImage").attr("src",path); }

生成驗證碼的程式碼

/**
     * 生成 驗證碼
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/getImage.do")
    public void getImage
(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out .println("#######################生成數字和字母的驗證碼#######################"); BufferedImage img = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB); // 得到該圖片的繪圖物件 Graphics g = img.getGraphics(); Random r = new Random(); Color c = new Color(200, 150, 255); g.setColor(c); // 填充整個圖片的顏色 g.fillRect(0, 0, 68, 22); // 向圖片中輸出數字和字母 StringBuffer sb = new StringBuffer(); char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); int index, len = ch.length; for (int i = 0; i < 4; i++) { index = r.nextInt(len); g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt (255))); g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22)); // 輸出的 字型和大小 g.drawString("" + ch[index], (i * 15) + 3, 18); // 寫什麼數字,在圖片 的什麼位置畫 sb.append(ch[index]); } request.getSession().setAttribute("piccode", sb.toString()); ImageIO.write(img, "JPG", response.getOutputStream()); }