SpringBoot通过Kaptcha配置验证码
SpringBoot配置验证码
kaptcha官网:https://code.google.com/archive/p/kaptcha/wikis/SpringUsage.wiki
-
导入pom依赖
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha --> <!-- 验证码--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
参考链接:https://mvnrepository.com/artifact/com.github.penggle/kaptcha/2.3.2
-
编写Kaptcha配置类
package com.peng.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"); //设置字体颜色 0,0,0 为黑色 properties.setProperty("kaptcha.textproducer.font.color","0,0,0"); //设置字符范围 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; } }
-
编写控制类
private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private Producer producer; /** * 生成验证码 */ @GetMapping("/kaptcha") public void getKaptcha(HttpServletResponse response, HttpSession session){ //生成验证码 String text = producer.createText(); BufferedImage image = producer.createImage(text); //将验证码存入session session.setAttribute("kaptcha",text); //将图片输出给浏览器 response.setContentType("image/png"); try { ServletOutputStream os = response.getOutputStream(); ImageIO.write(image,"png",os); } catch (IOException e) { logger.error("响应验证码失败:"+e.getMessage()); } }
-
在html中使用
<div class="col-sm-4">
<img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" class="mr-2"/>
<a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a>
</div>
<script>
function refresh_kaptcha(){
var path = "/kaptcha?p=" + Math.random();
$("#kaptcha").attr("src",path);
}
</script>
效果演示: