kaptcha生成验证码

kaptcha配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
public class KaptchaConfig {
    @Bean
    public Producer kaptchaProducer() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        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", "0l23456789ABCDEFGHIJKLMNOPQRSGUVWXYZ");//随机字符串
        properties.setProperty("kaptcha.textproducer.char.length", "4");//生成几个随机字符
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");//生成几个干扰
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

 生成验证码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Controller
public class LoginController{
 
    @Autowired
    private Producer kaptchaProducer;
    
    @RequestMapping(value = "/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 outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            logger.error("响应验证码失败:" + e.getMessage());
        }
    }
}

  页面显示,使用的为Thymeleaf模板引擎

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
</head>
<body
        <div>
            验证码:<input type="text" placeholder="请输入验证码!">
            <img th:src="@{/kaptcha}" id="kaptcha"/><a href="javascript:refresh_kaptcha()">刷新验证码</a>
        </div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
 
<script>
    function refresh_kaptcha() {
        var path = "/community/kaptcha?p=" + Math.random();
        $("#kaptcha").attr("src", path);
    }
</script>
</body>
</html>

  

posted @   小江麦子  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示