SpringBoot使用kaptcha验证码
在pom.xml配置
<!-- 验证码 -->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
配置kaptcha
package gm.config;
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 DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.textproducer.char.space", "5");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
前端视图的src链接处理,生成验证码
// 获取验证码
@GetMapping("/kaptcha")
public void kaptcha(HttpServletResponse response, HttpServletRequest request) throws Exception {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
String text = defaultKaptcha.createText();
BufferedImage image = defaultKaptcha.createImage(text);
request.getSession().setAttribute("code", text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.close();
}
还没有评论,来说两句吧...