①引入kapcha依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
②创建kapcha配置类配置验证码属性
@Configuration
public class KapchaConfig {
@Bean
Producer kapcha(){
Properties properties = new Properties();
properties.setProperty("kapcha.image.width","150");
properties.setProperty("kapcha.image.height","50");
//文本集合,验证码值从此集合中获取
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ");
//验证码长度
properties.setProperty("kaptcha.textproducer.char.length", "4");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
③定义接口
@RestController
public class ImageController {
@Autowired
private Producer producer;
@GetMapping("/img")
public void getVerifyCode(HttpServletResponse resp, HttpSession session){
resp.setContentType("image/jpeg");
String text = producer.createText();
session.setAttribute("code",text);
BufferedImage image = producer.createImage(text);
try {
ServletOutputStream outputStream = resp.getOutputStream();
ImageIO.write(image,"jpg",outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}