导入jar包
首先,还是老方法,在mvnrepository网站搜索kaptcha,添加到pom等待idea自动下载。
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
编写kaptcha配置类
新建一个config包,在包下新建KaptchaConfig类。
- 首先使用@Configuration注解定义配置类
- 从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
- 然后使用@Bean注解定义kaptchaProducer方法。
- 返回类型producer实际是一个接口,可以按住ctrl+鼠标左键点击Producer查看
- 使用的DefaultKaptcha类实现了Producer接口
- 使用properties配置kaptcha相关内容
- 验证码图片长宽
- 字体大小颜色
- 验证码字符范围,我使用0-9和大写的A-Z,长度为4
- 噪声配置,kaptcha生成的验证码图片本身已经是处理过,这里选择无噪声,也就是不加干扰
package com.neu.langsam.community.config;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@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","0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZ");
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;
}
}
生成随机字符,图片
我们在LoginController写生成验证码的请求。
- 因为这里返回的不是网页也不是字符串,所以我们传入HttpServletResponse自己返回
- 同时,生成验证码和图片后需要保存来核对,又是敏感数据,采用session
private static final Logger logger= LoggerFactory.getLogger(LoginController.class);
@Autowired
private Producer kaptchaProducer;
@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session){
//生成验证码
String text = kaptchaProducer.createText();
BufferedImage image = kaptchaProducer.createImage(text);
//将验证码存入session
session.setAttribute("kaptcha",text);
//将图片输出给浏览器
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
ImageIO.write(image,"png",os);
} catch (IOException e) {
logger.error("响应验证码失败"+e.getMessage());
}
}
运行项目,进入登录页面,前端js逻辑已经处理好了,所以可以直接正常显示。