javaweb基础之servlet下验证码的生成

一、利用工具包

  链接:https://pan.baidu.com/s/1oRhIBrIB_sYmpOsrmqaw9g 密码:6xwz

重要代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ValidateCode code = new ValidateCode(100,30,4,10);
		//2、获取生成的验证码的字符串值
		System.out.println(code.getCode());
	     //响应写的验证图片
		code.write(response.getOutputStream());
	}

ValidateCode的四个参数;       

  •   width:宽度
  •    height:高度偶几个
  •    codeCount:生成验证码有几个
  •    lineCount:有几条线,防止机器人识别,防止攻击网站

   二、利用jdk里面的类,自己生成验证码

重要代码:

  •  BufferedImage 在内存中生成一个指定大小,图片类型的图片:                                                                                                      BufferedImage(width,height, BufferedImage.TYPE_3BYTE_BGR);
  •  getGraphics();  创建一个画笔工具 
  •   drawRect(1, 1, width, height);         

ValidateCode2.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int width = 120;
		int height = 25;
		BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_3BYTE_BGR);
	    //创建画笔工具
		Graphics g = bi.getGraphics();
		g.setColor(Color.pink);
		g.setFont(new Font("宋体",Font.BOLD,18));
		//设置验证码的背景
		g.drawRect(1, 1, width, height);
		//设置随机数
		for(int i =0 ;i<4;i++){
		  int num = (int)(Math.random()*10);
		  //把生成的随机数放在图片上
		  g.drawString(num+"", 20*(i+1), 20);
		}
		//添加干扰线
		Random r = new Random();
		for(int i =0;i<10;i++){
			g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
		}
		
		//把创建的验证码图片响应给客户端
		ImageIO.write(bi, "JPG", response.getOutputStream());
	}

三、重要的网页代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
   function change(){
    var id=document.getElementById("code");
    /*  为了防止浏览器对于同一资源的缓存 */
    id.src="ValidateCode2?t="+Math.random();
   }
 </script>
</head>
<body>
<form action ="ValidateCode2" method="post">
   <input type="text" name="code"> </input>
   <img id="code" src="ValidateCode2" alt="验证码" onclick="change()"/>
   <a href="javascript:change()" >看不清,换一张 </a>
</form>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_42496678/article/details/82152996