登陆时验证码
1. 首先引入依赖
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
<scope>compile</scope>
</dependency>
2.由于项目使用的是springboot所以用的是@Configuration
@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; } }
3.在controller中使用,直接请求路径返回验证码 注意在写之前先注入 Producer 这个类
@Autowired
private Producer producer;
@RequestMapping("/captcha") public void captcha(HttpServletResponse response) throws IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); // 生成文字验证码 String text = producer.createText(); System.out.println("生成的验证码为:" + text); // 生成图片验证码 BufferedImage image = producer.createImage(text); //可以对生成的验证码保存到Session,或者redis中用做验证 //TODO ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); }
4.前端在请求的时候可以在请求路径上加上
'?useless=' + Math.random().toString(36).substr(2) 是为了能够随时刷新验证码

浙公网安备 33010602011771号