验证码工具-kaptcha

文章目录

简介

Kaptcha 是一个可高度配置的实用验证码生成工具,可*配置的选项如:

  • 验证码的字体
  • 验证码字体的大小
  • 验证码字体的字体颜色
  • 验证码内容的范围(数字,字母,中文汉字!)
  • 验证码图片的大小,边框,边框粗细,边框颜色
  • 验证码的干扰线
  • 验证码的样式(鱼眼样式、3D、普通模糊)

原文链接 (详细配置表)

原文链接

准备

  1. 新建一个SpringBoot项目
  2. 导入包
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

代码实现

1. KaptchaConfig

package com.zhx.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {

    @Bean(name = "kaptcha")
    public DefaultKaptcha getDefaultKaptcha() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        // 图片边框
        properties.setProperty("kaptcha.border", "yes");
        // 边框颜色
        properties.setProperty("kaptcha.border.color", "105,179,90");
        // 字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        // 图片宽
        properties.setProperty("kaptcha.image.width", "110");
        // 图片高
        properties.setProperty("kaptcha.image.height", "40");
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        // session key
        properties.setProperty("kaptcha.session.key", "code");
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 字体
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        kaptcha.setConfig(config);

        return kaptcha;
    }
}

2. KaptchaController

KaptchaController.java

package com.zhx.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;


/**
 * @author:ZhangHaiXia
 * @Date: 2022/3/2
 * @Description:
 */
@Controller
public class KaptchaController {
    /**
     * 验证码工具
     */
    @Autowired
    DefaultKaptcha kaptcha;

    /**
     * 返回首页
     * @return
     */
    @GetMapping(value = "/toLogin")
    public String index() {
        return "login";
    }

    @GetMapping("/getVerifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] verifyCode = null;
        ByteArrayOutputStream tempOut = new ByteArrayOutputStream();

        try {
            // 将生成的验证码保存在session中
            String text = kaptcha.createText();
            request.getSession().setAttribute("rightCode", text);
            BufferedImage bi = kaptcha.createImage(text);
            //使用ImageIo将流写入到tempOut中
            ImageIO.write(bi, "jpg", tempOut);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //将tempOut中的流转换为字节数组
        verifyCode = tempOut.toByteArray();
        //设置响应头
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        //响应回前端
        ServletOutputStream out = response.getOutputStream();
        out.write(verifyCode);
        out.flush();
        out.close();
    }



    /**
     * 验证码校验工具
     */
    @PostMapping(value = "/login")
    public ModelAndView verifyCheck(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView model = new ModelAndView();
        String rightCode = (String) request.getSession().getAttribute("rightCode");
        String tryCode = request.getParameter("tryCode");
        if (!rightCode.equals(tryCode)) {
            model.addObject("info", "验证码错误,请再输一次!");
            model.setViewName("login");

        } else {
            model.addObject("info", "登陆成功");
            model.setViewName("index");
        }
        return model;
    }
}

3. login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style type="text/css">
        body {
            padding: 10px;
        }
        #text1,#text2 {
            width: 100%;
        }
        #login{
            width: 300px;
            margin:0px auto;
            padding-top: 60px;
        }
        #flushimg{
            text-decoration: underline;
        }
        #butt{
            width: 60%;
        }
    </style>
</head>
<body>
<div id="login">
    <form action="/login" method="post">
        <h2 align="center">L O G I N</h2><br/><br/>
        <input type="text" name="userName" class="form-control" id="text1" required autofocus placeholder="-----请输入用户名-----"/><br/>
        <input type="password" name="userName" class="form-control" id="text2" required placeholder="----请输入用户密码----"/><br/>
        <div id="flushimg">
            <img alt="验证码" onclick="this.src='/getVerifyCode'" src="/getVerifyCode" />
            <a>看不清?点击图片刷新一下</a>
        </div>
        <input type="text" name="tryCode" class="form-control" required placeholder="-----请输入验证码-----" />
        <h4 th:text="${info}" style="color: red"></h4>
        <input type="checkbox" name="rememberMe"/>记住我<br/>
        <div style="width: 100%;text-align: center;"><input type="submit" value="登 录" id="butt" class="btn btn-success" /></div>
    </form>
</div>
</body>
</html>

4. index.html 登录成功

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>验证成功!</h2>
</body>
</html>
上一篇:msf下的各种生成payload命令


下一篇:零基础java自学流程-Java语言进阶189