java 生成验证码
1.引入maven依赖
<dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency>
2.配置属性
@Configuration
public class VerifyCodeConfig {
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border", "yes");//是否有边框
properties.put("kaptcha.textproducer.font.color", "blue");//背景颜色
properties.put("kaptcha.textproducer.char.space", "5");
properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");//字体
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.创建一个contoller:
@Controller public class ThymeleafController { @Autowired private Producer producer; @GetMapping("/get/verification/code") public void VerificationCode(HttpServletResponse response){ response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); String text = producer.createText(); //验证码内容可以保存数据库,并设置过期时间 BufferedImage image = producer.createImage(text); ServletOutputStream out=null; try { out= response.getOutputStream(); ImageIO.write(image, "jpg", out); }catch (Exception ex){ if(null!=out){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
4.浏览器访问:


浙公网安备 33010602011771号