servlet实现图片验证码

后端

生成图片验证码servlet:

@WebServlet("/verify")
public class VerificationCodeServlet extends BaseServlet {

    // 生成图片的宽度
    private int width;

    // 生成图片的高度
    private int height;

    // 验证码中字符的个数
    private int codeCount;

    // 基础码(用于生成随机验证码)
    private String code;

    @Override
    public void init() {
        width = Integer.parseInt(Configs.get("width"));
        height = Integer.parseInt(Configs.get("height"));
        codeCount = Integer.parseInt(Configs.get("code_count"));
        code = Configs.get("code");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); // 在内存中创建一张图片
        Graphics graphics = bi.getGraphics(); // 获取图片
        setBackground(graphics);
        setBorder(graphics);
        drawRandomLine(graphics);
        String verificationCode = generateVerificationCode();
        drawVerificationCode((Graphics2D) graphics, verificationCode);
        request.getSession().setAttribute("verificationCode", verificationCode); // 缓存验证码到session
        response.setContentType("image/jpeg"); // 设置响应头通知浏览器以图片的形式打开
        //设置响应头控制浏览器不要缓存
        response.setDateHeader("expired", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        ImageIO.write(bi, "jpg", response.getOutputStream()); // 响应输出图片
    }

    /**
     * 设置背景颜色
     *
     * @param graphics 图片
     */
    private void setBackground(Graphics graphics) {
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, width, height); // 填充区域
    }

    /**
     * 设置边框
     *
     * @param graphics 图片
     */
    private void setBorder(Graphics graphics) {
        graphics.setColor(Color.BLACK);
        graphics.drawRect(1, 1, width - 2, height - 2); // 边框区域
    }

    /**
     * 画随机线条
     *
     * @param graphics 图片
     */
    private void drawRandomLine(Graphics graphics) {
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < 3; i++) { // 设置线条个数并画线
            int x1 = new Random().nextInt(width);
            int y1 = new Random().nextInt(height);
            int x2 = new Random().nextInt(width);
            int y2 = new Random().nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 生成验证码
     *
     * @return 验证码
     */
    private String generateVerificationCode() {
        StringBuffer b = new StringBuffer();
        String codeChar;
        for (int i = 0; i < codeCount; i++) {
            codeChar = code.charAt(new Random().nextInt(code.length())) + "";
            b.append(codeChar);
        }
        return b.toString();
    }

    /**
     * 在图片上画验证码
     *
     * @param graphics 图片
     * @return String
     */
    private void drawVerificationCode(Graphics2D graphics, String verificationCode) {
        graphics.setColor(Color.BLACK);
        graphics.setFont(new Font("宋体", Font.BOLD, 20));
        int x = 5;
        for (int i = 0; i < verificationCode.length(); i++) {
            char codeChar = verificationCode.charAt(i);
            int degree = new Random().nextInt() % 30; // 设置字体的旋转角度
            graphics.rotate(degree * Math.PI / 180, x, 20); // 正向角度
            graphics.drawString(String.valueOf(codeChar), x, 20);
            graphics.rotate(-degree * Math.PI / 180, x, 20); // 反向角度
            x += 30;
        }
    }
}

属性配置properties文件:

#验证码图片相关配置
width=120
height=30
code_count=4
code=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ

配置信息类:

public class Configs {

    private static Properties configs;

    // 定义过滤文件对象(全局搜索文件并加载properties文件)
    private static FileFilter fileFilter = new FileFilter() {
        @Override
        public boolean accept(File file) {
            try {
                if (file.isDirectory()) {
                    file.listFiles(fileFilter);
                } else if (file.isFile() && file.getName().endsWith(".properties")) {
                    configs.load(new FileInputStream(file));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    };

    /**
     * 读取所有properties文件配置信息
     */
    static {
        configs = new Properties();
        ClassLoader classLoader = Configs.class.getClassLoader();
        File resourcesDir = new File(classLoader.getResource("").getPath());
        resourcesDir.listFiles(fileFilter);
    }

    private Configs() {
    }

    /**
     * 根据name查询相应配置信息值
     *
     * @param name 配置信息名
     * @return 配置信息值
     */
    public static String get(String name) {
        return configs.getProperty(name);
    }
}

前端(bootstrap + jquery)

html:

<div class="form-group">
    <label class="col-sm-offset-2 col-sm-2 control-label">验证码</label>
    <div class="col-sm-6">
        <div class="col-sm-5" style="float: left;">
            <input class="form-control" type="text" id="verificationCode" maxlength="4">
        </div>
        <div class="col-sm-5" style="float: right;">
            <img border="0" style="cursor:pointer" id="codeImage" alt="点击刷新验证码"
                 onclick="newCode()"
                 src="/api/verify">
        </div>
    </div>
</div>

js:

function newCode() {
    $("#codeImage").attr("src", baseUrl + "/verify?i=" + Math.random());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值