在一个web应用中验证码是一个常见的元素。不管是防止机器人还是爬虫都有一定的作用,我们是自己编写生产验证码的工具类,也可以使用一些比较方便的验证码工具。在网上收集一些资料之后,今天给大家介绍一下kaptcha的和springboot一起使用的简单例子。
准备工作:
1.你要有一个springboot的hello world的工程,并能正常运行。
2.导入kaptcha的maven:
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>开始实验:
我们有两种方式在springboot中使用kaptcha
第一种使用.xml的配置方式配置生成kaptcha的bean对象,在启动类上@ImportResource这个xml文件;在controller中注入其对象并使用
第二种是把kaptcha作为工程的一个类,加上@component注解在返回kaptcha的方法中加上@Bean注解,再在controller中注入其对象。
第一种方法:
在resources中创建一个xxx.xml文件 如:
mykaptcha.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://.google.code.kaptcha.impl.DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "yes"); properties.setProperty("kaptcha.border.color", "105,179,90"); properties.setProperty("kaptcha.textproducer.font.color", "blue"); properties.setProperty("kaptcha.image.width", "110"); properties.setProperty("kaptcha.image.height", "40"); properties.setProperty("kaptcha.textproducer.font.size", "30"); properties.setProperty("kaptcha.session.key", "code"); properties.setProperty("kaptcha.textproducer.char.length", "4"); properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } }注意要去掉启动类中引入的.xml文件,不然会有两个相同的对象,而你没有指明要注入哪一个的话启动会失败。
启动并测试:
到这里就算成功了。(也有使用jcaptcha的,只是他们最好不要再一个工程中使用,使用到了相同的类,有时候会导致异常。)
补充:对于kaptcha的配置属性大家可以找找,根据属性就可以配置了。
总结
以上所述是小编给大家介绍的SpringBoot 集成Kaptcha实现验证码功能实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!