【Java Web】使用Kaptcha生成验证码

1. 导入jar包

java 复制代码
<dependency>
	<groupId>com.github.penggle</groupId>
	<artifactId>kaptcha</artifactId>
	<version>2.3.2</version>
</dependency>

2. Kaptcha配置类

java 复制代码
package com.nowcoder.community.config;

import com.google.code.kaptcha.Producer;
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
    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.char.color", "black");  //颜色
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); // 字符
        properties.setProperty("kaptcha.textproducer.char.length", "4"); // 长度
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");  // 干扰方式

        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

3. Controller

java 复制代码
@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);

    // 将图片输出给浏览器
    response.setContentType("image/png");
    try{
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
    } catch (IOException e) {
        logger.error("响应验证码失败:"+e.getMessage());
    }
}

4. 前端刷新验证码

java 复制代码
<div class="col-sm-4">
	<img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" class="mr-2"/>
	<a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a>
</div>


<script>
	function refresh_kaptcha(){
		var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random();
		$("#kaptcha").attr("src",path);
	}
</script>
相关推荐
未来的JAVA高级开发工程师2 分钟前
spring的注入方式都有什么区别
java·spring
敲代码的瓦龙2 分钟前
C++?模板(进阶)!!!
开发语言·c++
User_芊芊君子3 分钟前
【Java多态】:灵活编程的核心
java·开发语言
_WndProc4 分钟前
【C++/控制台】简易五子棋游戏
开发语言·c++·游戏
谈不譚网安1 小时前
XXE(外部实体注入)
前端·网络安全
老K(郭云开)2 小时前
最新版Chrome浏览器调用ActiveX控件技术——alWebPlugin中间件V2.0.42版发布
前端·chrome·中间件
等等5432 小时前
Java EE初阶——定时器和线程池
java·java-ee
百锦再3 小时前
Vue环境下数据导出PDF的全面指南
前端·javascript·vue.js·python·django·pdf·pygame
IDRSolutions_CN3 小时前
如何在Java中处理PDF文档(教程)
java·经验分享·pdf·软件工程·团队开发
Sandman6z5 小时前
uv python 卸载
开发语言·python·uv