Javaweb 验证码 (彩色验证码详解)

31 篇文章 2 订阅
31 篇文章 2 订阅
这篇博客介绍了一个使用Java编写的后端验证码生成器。通过Servlet实现,生成的验证码图片包含随机字符和干扰线,防止浏览器缓存,并在HTTP响应中输出。前端页面展示了如何显示和刷新验证码图片,提供了点击更换验证码的功能。
摘要由CSDN通过智能技术生成

不多说,本人采用的是idea工具写的一个后端验证码全解,欢迎各位网友提出指导和修改

后台生成页面:

package com.util;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "VerifyCodeServle", urlPatterns = "/code")
public class VerifyCodeServle extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //防止浏览器缓存验证码
        response.setDateHeader("Expires", -1);
        response.setHeader("Cache-Control", "no-Cache");
        response.setHeader("pragma", "no-Cache");
        int width = 100;//验证码总宽度
        int height = 30;//验证码总高度
//         随机数
        char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();//字符串转换成字符数组
        String captcha = "";//定义一个临时路径
        Random random = new Random();//new 随机类Random
//         生成验证码图片(图片上下文对象)
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//         绘制矩形
        Graphics graphics = image.getGraphics();//绘制环境对象
        graphics.setColor(Color.gray);//设置背景色
        graphics.fillRect(0, 0, width, height);//绘制矩形
        //设定字体
        graphics.setFont(new Font("Times New Roman",Font.PLAIN,18));
        //随机生成155条干扰线,使图像中的认证不易被其它程序探测到
        graphics.setColor(getRandColor(160,200));
        for (int i=0;i<=155;i++){
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y2 = random.nextInt(12);
            //在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1) 和 (x2, y2) 之间画一条线。
            graphics.drawLine(x,y,x+x1,y+y2);
        }

//         随机生成4位数验证码图片
        for (int i = 0; i < 4; i++) {
            //设置随机数 - 数组
            int index = random.nextInt(codeChar.length);
            // 设置验证码字体图片颜色
            graphics.setColor(new Color(random.nextInt(110), random.nextInt(150), random.nextInt(200)));
            // 每个验证码字体的宽间距,高度
            graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
            captcha += codeChar[index];//把生成的验证码保存在临时变量中
        }
        request.getSession().setAttribute("codes", captcha); //把验证码保存在Session对象中
//         利用ImageI0输出验证码到页面中
        ImageIO.write(image, "jpg", response.getOutputStream());
        //关闭输入流
        response.getOutputStream().flush();
        response.getOutputStream().close();

    }
    Color getRandColor(int fc,int bc){//给定范围获得随机颜色
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
    }
}

前台展示页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>验证码</title>
    <script type="text/javascript">
        <!--验证码切换-->
        function changeImageCode() {
            document.getElementById('btn').isDisabled = true;
            document.getElementById('identity').src = 'code?ts=' + new Date().getTime();
        }
    </script>
</head>
<body>

 <image  src="code"  id="identity" onload="btn.disable=false;" style="cursor:pointer; vertical-align:middle"/>
 <input type="button" value="看不清,更换验证码" onclick="changeImageCode()" id="btn"  style="vertical-align:middle;border:0">

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值