JSP中验证码问题

来源:互联网 发布:linux怎么启动apache 编辑:程序博客网 时间:2024/05/22 09:51
  1. 以下代码随机产生四位数字的验证码:
    • 1)生成验证码的jsp代码:
<%@ page language="java" import="java.awt.*" contentType="image/jpeg"    import="java.awt.image.BufferedImage" import="java.util.*"    import="javax.imageio.*" pageEncoding="UTF-8"%><%    response.setHeader("Cache-Control", "no-cache");    // 在内存中创建图象     int width = 60, height = 20;    BufferedImage image = new BufferedImage(width, height,            BufferedImage.TYPE_INT_RGB);    //获取画笔    Graphics g = image.getGraphics();    //设定背景色     g.setColor(new Color(200, 200, 200));    g.fillRect(0, 0, width, height);    //取随机产生的验证码(4位数字)     Random rnd = new Random();    int randNum = rnd.nextInt(8999) + 1000;    String randStr = String.valueOf(randNum);    //将验证码存入session    session.setAttribute("randStr", randStr);    //将验证码显示到图象中     g.setColor(Color.black);    g.setFont(new Font("", Font.PLAIN, 20));    g.drawString(randStr, 10, 17);    // 随机产生100个干扰点,使图象中的验证码不易被其他程序探测到     for (int i = 0; i < 100; i++) {        int x = rnd.nextInt(width);        int y = rnd.nextInt(height);        g.drawOval(x, y, 1, 1);    }    // 输出图象到页面     ImageIO.write(image, "JPEG",response.getOutputStream());    out.clear();    out = pageContext.pushBody(); %>

登录界面显示验证码,点击 看不清,换一个 更换验证码

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登录</title></head><body>    <script language="javascript" type="text/javascript">        function refresh(imgUrl){            var getImgCode=document.getElementById("codeImg");            getImgCode.src=imgUrl+"?id="+Math.random();        }    </script>    欢迎登陆本系统!<br>    <form name="loginForm" action="login.jsp" method="post">        账号:<input type="text" name="account"/><br>        密码:<input type="password" name="password" /><br>        验证码:<input type="text" name="code" size="10" >        <img id="codeImg" name="codeImg" alt="验证码" src="validate.jsp" >        <a href="javascript:refresh('validate.jsp')">看不清,换一个</a><br>        <input type="submit" value="登录" >    </form></body></html>

效果图:
这里写图片描述