- 1.导入pom.xml
<!-- 生成验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
导入pom文件后开始写配置类。
- 2.配置类代码
config包下面新建一个kaptchaProducer类。
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 org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.naming.Context;
import javax.swing.text.DefaultEditorKit;
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","0123456789QWERTYUIOPASDFGHJKLZXCVBNM");//生成验证码的样本集合
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;
}
}
- 3.使用controller层对配置类进行测试
@Controller
public class kaptchaController {
@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
@ResponseBody
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());
}
}
}
- 4.运行项目进行测试: