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;
/**
* 生成验证码配置
*/
@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;
}
}
依赖:
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
使用
import com.google.code.kaptcha.Producer;
import com.rdss.back.model.entity.SysCaptchaEntity;
import com.rdss.back.service.SysCaptchaService;
import com.rdss.common.exception.RdssException;
import com.rdss.common.service.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;
/**
* 验证码
*
* @author Mark sunlightcs@gmail.com
* @since 2.0.0 2018-02-10
*/
@Service
public class SysCaptchaServiceImpl implements SysCaptchaService {
@Autowired
private Producer producer;
@Autowired
private RedisService redisService;
private final String UUID_CODE_PRE="captcha_code_pre:";
//验证码有效期:单位秒
@Value("${rdss.auth.captcha-storage.expire}")
private int expire;
@Override
public BufferedImage getCaptcha(String uuid) {
if(StringUtils.isBlank(uuid)){
throw new RdssException("uuid不能为空");
}
//生成文字验证码
String code = producer.createText();
SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
captchaEntity.setUuid(uuid);
captchaEntity.setCode(code);
captchaEntity.setExpire(expire);
redisService.setStr(UUID_CODE_PRE+uuid,code,expire, TimeUnit.SECONDS);
return producer.createImage(code);
}
@Override
public boolean validate(String uuid, String code) {
String savedCode = redisService.getStr(UUID_CODE_PRE+uuid);
redisService.del(UUID_CODE_PRE+uuid);
if(StringUtils.isNotBlank(savedCode)&&savedCode.equalsIgnoreCase(code) ){
return true;
}
return false;
}
}
redis用Spring注入
@Autowired
StringRedisTemplate stringRedisTemplate;