kaptcha验证码使用笔记/Spring boot

导包还是要提一下的 

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

有拦截器的童鞋 记得放过return  true 

<img id="captcha" src="/captcha.jpg" width="116" height="36" onclick="refreshCode(this)">

顺便附上js刷新代码,可有可无...

//刷新验证码
function refreshCode(){
    var captcha = document.getElementById("captcha");
    captcha.src = "/captcha.jpg?t=" + new Date().getTime();
}

后台路径Controller  处理一下 

@Autowired
private Producer producer;


@RequestMapping("/captcha.jpg")
public void captcha(HttpServletResponse response,HttpServletRequest request)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setCharacterEncoding("utf-8");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到 session

        request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

验证嘛就是取出来就是了,也贴一下把

  String kaptcha =(String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if(!captcha.equalsIgnoreCase(kaptcha)){
            map.put("code",-1);
            map.put("msg","验证码不正确");
            return map;
        }

因为用的Spring boot 还有一个配置类,有兴趣的童鞋可以细细挖掘一下

/**
 * 生成验证码配置
 */
@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

还在开发项目中,就草草make一下

猜你喜欢

转载自blog.csdn.net/qq_16513911/article/details/81981949