Day76-Spring Boot实践,开发社区登录模块-生成二维码

Day76-Spring Boot实践,开发社区登录模块-生成二维码

一.Kaptcha

1.1导入jar包

<!--Kpatcha 生成验证码-->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

1.2编写Kaptcha配置类

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.font.color","0,0,0");
        properties.setProperty("Kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ");
        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;
    }



}

1.3生成随机字符,生成图片

@RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //生成验证码
        String text = kpatchaProducer.createText();
        BufferedImage image = kpatchaProducer.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());
        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿杰杰杰のblog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值