java springboot 使用Kaptcha组件实现验证码功能

Kaptcha组件实现验证码

一、pom.xml中引入Kaptcha 的maven依赖

    <dependency>
        <groupId>com.github.pengglegroupId>
        <artifactId>kaptchaartifactId>
        <version>2.3.2version>
    dependency>

二、Kaptcha 配置

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

import java.util.Properties;

@Component
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        DefaultKaptcha defaultKaptcha = 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", "blue");
        properties.setProperty("kaptcha.image.width", "110");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

具体样式参数如下

Constant 描述 默认值
kaptcha.border 图片边框,合法值:yes , no yes
kaptcha.border.color 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue black
kaptcha.border.thickness 边框厚度,合法值:>0 1
kaptcha.image.width 图片宽 200
kaptcha.image.height 图片高 50
kaptcha.producer.impl 图片实现类 com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl 文本实现类 com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string 文本集合,验证码值从此集合中获取 abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 验证码长度 4
kaptcha.textproducer.font.names 字体 Arial, Courier
kaptcha.textproducer.font.size 字体大小 40px.
kaptcha.textproducer.font.color 字体颜色,合法值: r,g,b 或者 white,black,blue black
kaptcha.textproducer.char.space 文字间隔 2
kaptcha.noise.impl 干扰实现类 com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color 干扰 颜色,合法值: r,g,b 或者 white,black,blue black
kaptcha.obscurificator.impl 图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple, 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy, 阴影com.google.code.kaptcha.impl.ShadowGimpy com.google.code.kaptcha.impl.WaterRipple
kaptcha.background.impl 背景实现类 com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from 背景颜色渐变,开始颜色 light grey
kaptcha.background.clear.to 背景颜色渐变, 结束颜色 white
kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.key session key KAPTCHA_SESSION_KEY
kaptcha.session.date session date KAPTCHA_SESSION_DATE

三、定义控制类

@Controller
public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 生成验证码
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws IOException
     */
    @RequestMapping("/getCodeImage")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        byte[] captchaChallengeAsJpeg = null;
        ByteOutputStream byteOutputStream = new ByteOutputStream();
        // 生产验证码字符串并保存到session中
        String createText = defaultKaptcha.createText();
        httpServletRequest.getSession().setAttribute("rightCode",createText);
        // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage bufferedImage = defaultKaptcha.createImage(createText);
        try {
            ImageIO.write(bufferedImage,"jpg",byteOutputStream);
        } catch (IOException e) {
            System.out.println("------验证码图片输出错误-------------");
        }
        // 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = byteOutputStream.getBytes();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 检查验证码是否正确
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    @RequestMapping("/verifyCode")
    public ModelAndView verifyCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        ModelAndView modelAndView = new ModelAndView();
        String rightCode = httpServletRequest.getSession().getAttribute("rightCode").toString();
        String tryCode = httpServletRequest.getParameter("tryCode");
        System.out.println("rightCode:"+rightCode+" ———— tryCode:"+tryCode);
        if(rightCode.equals(tryCode)){
            modelAndView.addObject("info","登录成功");
            modelAndView.setViewName("success");
        }
        else{
            modelAndView.addObject("info","验证码输入错误");
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }
}

四、前端页面

使用thymeleaf模板



<html xmlns:th="http://www.thymeleaf.org">
    <head lang="en">
        <meta charset="UTF-8">meta>
        <title>Kaptcha实现验证码功能title>
    head>
    <style type="text/css">
        body {
            padding: 10px
        }
    style>
    <body>
        
        <h3 th:text="${info}">h3>
        <div>
            <img alt="验证码" id="imageCode" src="/demo/getCodeImage" />
            <a href="javascript:reloadCode();">看不清楚,换一张a>
        div>
        <form action="/demo/verifyCode" >
            <input type="text" name="tryCode" />
            <input type="submit" value="提交">input>
        form>
    body>
    
    <script type="text/javascript">
        function reloadCode() {
            document.getElementById("imageCode").src="/demo/getCodeImage?d='+new Date()*1";
        }
    script>
html>


<html>
    <head>
        <meta charset="UTF-8">meta>
        <title>验证成功title>
    head>
    <body>
        <h1>验证成功h1>
    body>
html>

你可能感兴趣的:(SpringBoot)