javaweb 驗證碼實現

驗證碼(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自動區分計算機和人類的圖靈測試)的縮寫,是一種區分用戶是計算機還是人的公共全自動程序。可以防止:惡意破解密碼、刷票、論壇灌水,有效防止某個黑客對某一個特定註冊用戶用特定程序暴力破解方式進行不斷的登陸嘗試,實際上用驗證碼是現在很多網站通行的方式,我們利用比較簡易的方式實現了這個功能。

實現驗證碼功能需要創建以下文件:

VerifyCodeUtil.java:驗證碼工具類。

VerifyCodeController.java:獲取驗證碼的控制層。

login.html:頁面獲取驗證碼以及展示。

進入正題,上代碼:

VerifyCodeUtil.java

/**
 * 驗證碼工具類
 */
public class VerifyCodeUtil {
	
	/**
	 * 繪畫驗證碼
	 */
	public String drawImg(ByteArrayOutputStream output){
		String code = "";
		for(int i=0; i<4; i++){
			code += randomChar();
		}
		int width = 70;
		int height = 25;
		BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Times New Roman",Font.PLAIN,20);
		Graphics2D g = bi.createGraphics();
		g.setFont(font);
		Color color = new Color(66,2,82);
		g.setColor(color);
		g.setBackground(new Color(226,226,240));
		g.clearRect(0, 0, width, height);
		FontRenderContext context = g.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(code, context);
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = bounds.getY();
		double baseY = y - ascent;
		g.drawString(code, (int)x, (int)baseY);
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return code;
	}
	
	/**
	 * 隨機參數字符
	 */
	private char randomChar(){
		Random r = new Random();
		String s = "qwertyuioplkjhgfdsazxcvbnm0123456789";
		return s.charAt(r.nextInt(s.length()));
	}
}

VerifyCodeController.java

/**
 * 驗證碼控制層
 */
@Controller
@RequestMapping("/verifyCode")
public class VerifyCodeController{
	
	/**
	 * 獲取驗證碼
	 */
	@RequestMapping(value="/getVerifyCode", method={RequestMethod.POST, RequestMethod.GET})
	public void getVerifyCode(HttpServletResponse response, HttpSession session){
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		
		VerifyCodeUtil vcu = new VerifyCodeUtil();
		
		String verifyCode = vcu.drawImg(output);
		
		session.setAttribute("verifyCode", verifyCode);
		
		try {
			
			ServletOutputStream out = response.getOutputStream();
			
			output.writeTo(out);
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

}
<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-clearmin.min.css">
    <link rel="stylesheet" type="text/css" href="css/roboto.css">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
    <title>歡迎使用${title}系統</title>
    <style></style>
  </head>
  <body class="cm-login">

    <div class="text-center" style="padding:90px 0 30px 0;background:#fff;border-bottom:1px solid #ddd">
      <img src="img/logo-big.svg" width="300" height="45">
    </div>
    
    <div class="col-sm-6 col-md-4 col-lg-3" style="margin:40px auto; float:none;">
      <form method="post" action="index.html">
		<div class="col-xs-12">
          <div class="form-group">
		    <div class="input-group">
		      <div class="input-group-addon"><i class="fa fa-fw fa-user"></i></div>
		      <input type="text" name="username" class="form-control" placeholder="請輸入用戶名">
		    </div>
          </div>
          <div class="form-group">
		    <div class="input-group">
		      <div class="input-group-addon"><i class="fa fa-fw fa-lock"></i></div>
		      <input type="password" name="password" class="form-control" placeholder="請輸入密碼">
		    </div>
          </div>
          <div class="form-group">
		    <div class="input-group">
		      <div class="input-group-addon"><i class="fa fa-picture-o"></i></div>
		      <input class="form-control" style="width:150px;" type="text" id="verifyCode" name="verifyCode" placeholder="驗證碼" maxlength="4">
		      <img style="position: absolute;right: 0;top: 0;" id="imgVerifyCode" alt="點擊更換驗證碼" title="點擊更換驗證碼" src="" width="105" height="34">
		    </div>
          </div>
        </div>
		<div class="col-xs-6">
	          <div class="checkbox"><label><input type="checkbox"> 記住我</label></div>
		</div>
		<div class="col-xs-6">
	          <button type="submit" class="btn btn-block btn-primary">登錄</button>
        </div>
      </form>
    </div>
    <script type="text/javascript" src="js/lib/jquery-2.1.3.min.js"></script>
    <script type="text/javascript">
    $(function(){
    	changeCode();//第一次獲取驗證碼
		$("#imgVerifyCode").bind("click", changeCode);//綁定onclick事件,調用changeCode方法
    	
    });
    
    function changeCode(){
		$("#imgVerifyCode").attr("src", "/azzan_spb/verifyCode/getVerifyCode?t=" + genTimestamp());
	}
    
    function genTimestamp() {
		var time = new Date();
		return time.getTime();
	}
    </script>
  </body>
</html>

效果圖:

各位看官,如果能幫助到你,記得點贊哦!!!!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章