项目开发日志——Kaptcha验证码

我们经常会发现在其他网站登录的时候要求输入一些验证码来验证是不是人机,利用Kaptcha就可以实现。

Kaptcha有一个Produce接口,其中有两个方法:

public interface Producer {
    
    java.awt.image.BufferedImage createImage(java.lang.String s);

    java.lang.String createText();
}

同时,也有一个DefaultKaptcha类继承了Configuration类并实现了Producer接口,我们可以创建properties对象,传入配置参数,然后传入config对象,再利用DefaultKaptcha对象的setConfig方法来生成验证码

@Configuration
public class KaptchaConfig {
    @Bean  //服务器启动时会自动装配到容器中,通过容器可以得到Producer实例
    public Producer kaptchaProducer() {
        //创建属性对象
        Properties properties = new Properties();
        //设置图片宽度
        properties.setProperty("kaptcha.image.width", "100");
        //设置图片高度
        properties.setProperty("kaptcha.image.height", "40");
        //设置字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "32");
        //设置字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");
        //设置生成随机字符的范围
        properties.setProperty("kaptcha.textproducer.char.string",
                                "0123456789ABCDEFGHIGKLMN");
        //设置生成随机字符的数量
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        //添加噪声干扰
        properties.setProperty("kaptcha.noise.impl",
                                "com.google.code.kaptcha.impl.NoNoise");
        //生成kaptcha对象
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        //创建config对象,并将properties对象作为参数传入
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

在Controller层可以生成验证码并返回给浏览器

@Autowired
private Producer kaptchaProducer;

//生成验证码
@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session) {
    //生成随机文本
    String text = kaptchaProducer.createText();
    //生成图片
    BufferedImage image = kaptchaProducer.createImage(text);
    //将验证码存入session
    session.setAttribute("kaptcha", text);
    //将图片返回给客户端
    //  1. 先声明返回的是什么类型
    response.setContentType("image/png");
    //  2. 输出流向浏览器输出
    try {
        OutputStream os = response.getOutputStream();
        ImageIO.write(image,"png",os);
    } catch (IOException e) {
        logger.error("响应验证码失败" + e.getMessage());
    }
}

在login页面中编写接收并显示验证码的代码如下:

<div>
    <img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" />
    <a href="javascript:refresh_kaptcha();" >刷新验证码</a>
</div>
<script>
    function refresh_kaptcha() {
    var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random();
    $("#kaptcha").attr("src", path);
    }
</script>
posted @ 2022-10-15 21:26  Shineloner  阅读(105)  评论(0)    收藏  举报