1.引入jar
compile('com.github.penggle:kaptcha:2.3.2')
2.Captcha配置
package com.xxx.common.captcha;
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;
/**
* Created by zhangmy on 2017/8/9.
*/
@Configuration
public class CaptchaConfig {
@Bean
public DefaultKaptcha getKaptchaBean() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
//边框样式
properties.setProperty("kaptcha.border", "yes");
properties.setProperty("kaptcha.border.color", "105,179,90");
//验证码颜色
properties.setProperty("kaptcha.textproducer.font.color", "red");
//图片长宽
properties.setProperty("kaptcha.image.width", "130");
properties.setProperty("kaptcha.image.height", "50");
//字符大小
properties.setProperty("kaptcha.textproducer.font.size", "40");
properties.setProperty("kaptcha.session.key", "code");
//设置字体个数
properties.setProperty("kaptcha.textproducer.char.length", "5");
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.获取验证码,将验证码以cookie的形式存储到客户端,将服务器生成的验证码放到redis
package com.xxx.common.captcha;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xxx.core.exception.ServiceException;
import com.xxx.core.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Created by zhangmy on 2