Day76-Spring Boot实践,开发社区登录模块-生成二维码
一.Kaptcha
1.1导入jar包
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
1.2编写Kaptcha配置类
package com.nowcoder.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","0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ");
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;
}
}
1.3生成随机字符,生成图片
@RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session){
String text = kpatchaProducer.createText();
BufferedImage image = kpatchaProducer.createImage(text);
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());
}
}