springboot生成图形验证码

pom.xml

        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

 

KaptchaConfig.java
package com.example.demo.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,255");
        // 验证码的字符在哪个范围里随机产生
        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;
    }
}

 

控制器:


@Autowired
private Producer kaptchaProducer;

@RequestMapping(path = "/kaptcha", method = RequestMethod.GET) public void getKaptcha(HttpServletResponse httpServletResponse, HttpSession httpSession) throws BizException { // 生成验证码 String text = kaptchaProducer.createText(); BufferedImage image = kaptchaProducer.createImage(text); // 将验证码存入session httpSession.setAttribute("kaptcha", text); // 将图片输出给浏览器 httpServletResponse.setContentType("image/png"); try { OutputStream os = httpServletResponse.getOutputStream(); ImageIO.write(image, "png", os); } catch (IOException e) { throw new BizException(1, "响应验证码失败"); } }

 



前端:
<li valign="top">验证码: <img src="/kaptcha" /></li>

 

效果:

 

posted @ 2023-02-09 17:03  河北大学-徐小波  阅读(177)  评论(0编辑  收藏  举报