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>

效果图:

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

实现JavaWeb登录验证码,可以采用以下步骤: 1. 在登录页面中添加验证码输入框和图片显示框。 2. 生成随机的验证码字符串。 3. 把验证码字符串保存到session中。 4. 在后台生成一张验证码图片,并把验证码字符串画到图片上。 5. 把图片输出到前台显示。 6. 用户输入验证码后,后台从session中取出保存的验证码字符串进行比对,验证是否正确。 下面是一个简单的示例代码: 1. 登录页面login.jsp: ```html <form action="login" method="post"> <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <label>验证码:</label> <input type="text" name="verifyCode"> <img src="verifyCode" onclick="this.src='verifyCode?'+Math.random()"><br> <input type="submit" value="登录"> </form> ``` 2. 后台生成验证码的Servlet: ```java @WebServlet("/verifyCode") public class VerifyCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应的类型格式为图片格式 response.setContentType("image/jpeg"); // 创建验证码对象 VerifyCode verifyCode = new VerifyCode(); // 把验证码字符串保存到session中 HttpSession session = request.getSession(); session.setAttribute("verifyCode", verifyCode.getCode()); // 把验证码图片输出到前台 verifyCode.write(response.getOutputStream()); } } ``` 3. 验证验证码的Servlet: ```java @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户输入的验证码和保存在session中的验证码字符串 String verifyCode = request.getParameter("verifyCode"); HttpSession session = request.getSession(); String sessionVerifyCode = (String) session.getAttribute("verifyCode"); // 比对验证码是否正确 if (!verifyCode.equalsIgnoreCase(sessionVerifyCode)) { response.getWriter().println("验证码错误!"); return; } // 验证通过,继续登录验证逻辑... } } ``` 其中,VerifyCode是一个生成验证码图片的辅助类,可以参考下面的代码实现: ```java public class VerifyCode { private static final int WIDTH = 120; // 验证码图片宽度 private static final int HEIGHT = 40; // 验证码图片高度 private static final int CODE_LENGTH = 6; // 验证码长度 private static final String CODE_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 验证码字符集 private String code; // 验证码字符串 public VerifyCode() { // 生成随机的验证码字符串 StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < CODE_LENGTH; i++) { sb.append(CODE_CHARS.charAt(random.nextInt(CODE_CHARS.length()))); } this.code = sb.toString(); } public String getCode() { return code; } public void write(OutputStream os) throws IOException { // 创建验证码图片 BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); g.setColor(Color.BLACK); g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1); g.setFont(new Font("宋体", Font.BOLD, 20)); for (int i = 0; i < code.length(); i++) { g.drawString(String.valueOf(code.charAt(i)), 20 * i + 10, 25); } // 输出验证码图片 ImageIO.write(image, "JPEG", os); os.flush(); os.close(); } } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值