验证码的生成和使用

来源:互联网 发布:windows exe elf 编辑:程序博客网 时间:2024/06/01 10:22

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");}



0 0
原创粉丝点击