javaweb 验证码实现

验证码是区分用户是计算机还是人的公共全自动程序,可防止恶意破解密码等。本文利用简易方式实现该功能,需创建VerifyCodeUtil.java、VerifyCodeController.java和login.html文件,并给出了相关代码及效果图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

验证码(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>

效果图:

各位看官,如果能帮助到你,记得点赞哦!!!!!!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值