验证码的生成和使用

1.jsp页面

验证码<input name="checkcode" type="text">
<img src="imageServlet" id="imageCode" alt="验证码" title="验证码">
<a href="javaScript:reLoadCode()">看不清</a><br/>

<script type="text/javascript">
	alert("欢迎登录");
	function reLoadCode(){
	var time = new Date().getTime();
	document.getElementById("imageCode").src="imageServlet?id="+time;
	}
</script>

2.imageServlet用于生成验证码,且把生成的验证码以session形势保存


public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {


		/*1、BufferedImage图像数据缓冲区


		2、Graphics绘制图片


		3、Color获取颜色


		4、Random生成随机数


		5、ImageIo输出图片*/
		BufferedImage bi = new BufferedImage(70, 40, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.getGraphics();
		Color c = g.getColor();
		g.setColor(Color.yellow);
		g.fillRect(0, 0, 70, 40);
		char[] ch= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<4; i++) {
			int index = r.nextInt(ch.length);
			Font f = new Font("宋体", Font.BOLD, 40);
			g.setFont(f);
			g.setColor(new Color(r.nextInt(255),r.nextInt(255), r.nextInt(255)));
			g.drawString(ch[index]+"", i*15+3, 28);
			sb.append(ch[index]);
		}
		request.getSession().setAttribute("pop", sb.toString());
		ImageIO.write(bi, "JPG", response.getOutputStream());


	}



3.表单提交到的servlet,负责把验证码从session中得到并与提交的用户填写的验证码比较


String s1 = (String) request.getSession().getAttribute("pop");
		String s2 = request.getParameter("checkcode");

if(true == flag && s1.equalsIgnoreCase(s2)) {
			//if(c.equalsIgnoreCase(parm))
				out.write("success");
		}
		else {
			out.write("error");
		}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值