<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
package com.zichan360.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
Producer getCaptchaProducer(){
DefaultKaptcha producer = new DefaultKaptcha();
Properties properties = new Properties();
properties.put("kaptcha.border", "yes");
properties.put("kaptcha.border.color", "105,179,90");
properties.put("kaptcha.textproducer.font.color", "blue");
properties.put("kaptcha.image.width", "125");
properties.put("kaptcha.image.height", "45");
properties.put("kaptcha.textproducer.font.size", "40");
properties.put("kaptcha.session.key", "code");
properties.put("kaptcha.textproducer.char.length", "4");
properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
producer.setConfig(new Config(properties));
return producer;
}
}
@GetMapping(value = "/captcha")
public Result getCaptcha() throws Exception {
HttpSession session = httpServletRequest.getSession();
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setContentType("image/jpeg");
String capText = captchaProducer.createText();
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = httpServletResponse.getOutputStream();
ImageIO.write(bi, "jpg", out);
byte[] result = new byte[]{};
out.write(result);
try {
out.flush();
} finally {
out.close();
}
return null;
}
if (!captcha.equals(session.getAttribute(Constants.KAPTCHA_SESSION_KEY))) {
return ResultUtil.sendErrorMessage("图形验证码有误!");
}
session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);