利用kaptcha生成登录验证码
作者:互联网
利用kaptcha生成登录验证码
导入包
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
由于spring没有整合kaptcha,自定义一个katcha的配置类
@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");
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);
@Autowired
Producer 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);
//将验证码存入session
session.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的返回结果
标签:登录,kaptcha,image,验证码,public,setProperty,properties 来源: https://www.cnblogs.com/zzkkyy/p/15866004.html