SpringBoot使用kaptcha验证码
更新于2023-02-27
| 技术笔记
| 浏览(162)
| 评论(0)
- 1.引入kaptcha所需要的jar包
- <dependency>
- <groupId>com.github.penggle</groupId>
- <artifactId>kaptcha</artifactId>
- <version>2.3.2</version>
- </dependency>
- 2.配置kapcha
- @Configuration
- public class CaptchaConfig {
- @Bean(name="captchaProducer")
- public DefaultKaptcha getKaptchaBean(){
- 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.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;
- }
- }
- 3.Controller中这样使用
- @RequestMapping(value = "/captcha-image")
- public ModelAndView getKaptchaImage(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- 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();
- System.out.println("capText: " + capText);
- try {
- String uuid=UUIDUtils.getUUID32().trim().toString();
- redisTemplate.opsForValue().set(uuid, capText,60*5,TimeUnit.SECONDS);
- Cookie cookie = new Cookie("captchaCode",uuid);
- response.addCookie(cookie);
- } catch (Exception e) {
- e.printStackTrace();
- }
- BufferedImage bi = captchaProducer.createImage(capText);
- ServletOutputStream out = response.getOutputStream();
- ImageIO.write(bi, "jpg", out);
- try {
- out.flush();
- } finally {
- out.close();
- }
- return null;
- }
- 4.前台这样用
- <img style="height:22px;" id="codeImg" alt="点击更换" title="点击更换" src="code/captcha-image" />
点赞 0
打赏
微信赞赏
支付宝赞赏