简单生成验证码,在Servlet和ssm框架中都可以用。

首先在jsp页面要展示生成的验证码,代码如下:

<form action="${pageContext.request.contextPath }/CheckCodeServlet" method="post">
    请输入验证码:<input type="text" name="code">
    <input type="submit" value="确定">
</form>
<img alt="验证码" id="scode" src="${pageContext.request.contextPath }/ImageServlet" >
<a href="#" οnclick="javascript:flushCode();">看不清?</a>

<script type="text/javascript">
function flushCode() {
    // 每次刷新的时候获取当前时间,防止浏览器缓存刷新失败
    var time = new Date();
    document.getElementById("scode").src = "${pageContext.request.contextPath }/ImageServlet?time=" + time;
}
</script>

然后需要在Servlet写一个生成验证码的案例,如果使用ssm框架,只需改变请求路径
以下是在Servlet中,代码如下:

@WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
	  // 图片高度
    private static final int IMG_HEIGHT = 100;
    // 图片宽度
    private static final int IMG_WIDTH = 30;
    // 验证码长度
    private static final int CODE_LEN = 4;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 用于绘制图片,设置图片的长宽和图片类型(RGB)
        BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
        // 获取绘图工具
        Graphics graphics = bi.getGraphics();
        graphics.setColor(new Color(100, 230, 200)); // 使用RGB设置背景颜色
        graphics.fillRect(0, 0, 100, 30); // 填充矩形区域
        // 验证码中所使用到的字符
        char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
        String captcha = ""; // 存放生成的验证码
        Random random = new Random();
        for(int i = 0; i < CODE_LEN; i++) { // 循环将每个验证码字符绘制到图片上
            int index = random.nextInt(codeChar.length);
            // 随机生成验证码颜色
            graphics.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(255)));
            // 将一个字符绘制到图片上,并制定位置(设置x,y坐标)
            graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
            captcha += codeChar[index];
        }
        // 将生成的验证码code放入sessoin中
        req.getSession().setAttribute("code", captcha);
        // 通过ImageIO将图片输出
        ImageIO.write(bi, "JPG", resp.getOutputStream());
    }

}

最后需要验证输入的验证码是否保持一致,并且不区分大小写:

@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 获取存放在session中的验证码
        String code = (String) req.getSession().getAttribute("code");
        // 获取页面提交的验证码
        String inputCode = req.getParameter("code");
        if(code.toLowerCase().equals(inputCode.toLowerCase())) {// 验证码不区分大小写
            // 验证成功,跳转到成功页面
            req.getRequestDispatcher("/success.jsp").forward(req, resp);
        } else { // 验证失败
            req.getRequestDispatcher("/fail.jsp").forward(req, resp);
        }
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值