记录一下最近关于登录过程中,图片验证码和阿里的手机短信功能。
1.图片验证码
图片验证码是使用com.google.code.kaptcha第三方包来实现的,但是由于是google的jar包,所以在国内,Maven是下载不了,但好在有大佬在github中分享了(感谢大佬!,感谢开源!)。
Maven中依赖:
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
主要代码:
@Autowired
private Producer producer;
@RequestMapping("captcha")
public void captcha(HttpServletResponse response) throws IOException{
//生成文字验证码
String text = producer.createText();
//生成图片验证
BufferedImage image = producer.createImage(text);
//一般需要将验证码放到redis中,供之后验证使用
//J2CacheUtils.put(Constants.KAPTCHA_SESSION_KEY,text);
//将图片传到前台
ServletOutputStream out = response.getOutputStream();
ImageIo.write(image,"jpg",out);
}
在这过程中会出现Producer的自动装载问题,提示Producer不能自动装载,这里解决的方案就是手动装载。
编写WebConfig工具类
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
@Configuration
public class WebConfig {
@Bean
public Producer KaptchaProducer() {
Properties kaptchaProperties = new Properties();
kaptchaProperties.put("kaptcha.border"