利用kaptcha生成登录验证码
导入包
<dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency>
由于spring没有整合kaptcha,自定义一个katcha的配置类
@Configuration
public class KaptchaConfig {@Beanpublic 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");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;}
}
定义一个/kaptcha接口来返回验证码图片
@Controller
public class HomeController {Logger logger = LoggerFactory.getLogger(HomeController.class);@AutowiredProducer kaptcherProducer;//Producer是kaptcha的核心接口,通过它去创建图片以及随机的字符串@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)public void getKaptcha(HttpServletResponse response, HttpSession session){//生成验证码String text = kaptcherProducer.createText();BufferedImage image = kaptcherProducer.createImage(text);//将验证码存入sessionsession.setAttribute("kaptcha", text);//将图片输出到浏览器response.setContentType("image/png");try{ServletOutputStream outputStream = response.getOutputStream();ImageIO.write(image,"png",outputStream);}catch (IOException e){logger.error("响应验证码失败:" + e.getMessage());}}}
输入http://localhost:8080/kaptcha的返回结果