谷歌 captcha 验证码生成工具

1.用于生成验证码的图片

a.pom

 
        
            com.github.penggle
            kaptcha
            2.3.2
        
b.bean
@Configuration
public class ComponentConfig {

    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "125");
        properties.setProperty("kaptcha.image.height", "45");
        properties.setProperty("kaptcha.textproducer.font.size", "45");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

c.controller

@Slf4j
@RestController
@RequestMapping
public class SampleController {

    public static final String ROOT_PATH = "/test";


    @Autowired
    private SampleService sampleService;

    @Autowired
    private DefaultKaptcha captchaProducer = null;

    /**
     * 验证码生成接口
     * 127.0.0.1:8081/captcha
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "captcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}

测试:

谷歌 captcha 验证码生成工具_第1张图片

你可能感兴趣的:(谷歌 captcha 验证码生成工具)