1.controller
/**
* 获取随机数验证码图片
*
* @param request HttpServletRequest
* @param response HttpServletResponse
*/
@GetMapping(value = "/getRandomCode" ,produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void getRandomCode(HttpServletRequest request, HttpServletResponse response) {
baseService.getRandomCode(request, response);
}
2.service
void getRandomCode(HttpServletRequest request, HttpServletResponse response);
3.serviceImpl
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private CodeImageUtils codeImageUtils;
/**
* 获取随机数验证码图片
*/
@Override
public void getRandomCode(HttpServletRequest request, HttpServletResponse response) {
try {
// 设置输出类型为图片
response.setContentType("image/jpeg");
// 生成随机码
String verificationCode = codeImageUtils.getRandomCode();
// 背景颜色与字符颜色
Color color = codeImageUtils.getRandomColor();
Color reverseColor = codeImageUtils.getReverseColor(color);
//创建一张彩色的图片
BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bi.createGraphics();
//设置字体
graphics.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
graphics.setColor(color);
//绘制背景
graphics.fillRect(0, 0, 100, 30);
graphics.setColor(reverseColor);
//绘制字符
graphics.drawString(verificationCode, 18, 20);
//绘制最多50个随机噪点//绘制最多50个随机噪点
Random random = new Random();
int n = random.nextInt(50);
for (int i = 0; i < n; i++) {
graphics.drawRect(100, 30, 1, 1);
}
// 放到redis中 sessionId:code,过期时间60s
redisTemplate.opsForValue().set(request.getSession().getId(),verificationCode,60, TimeUnit.SECONDS);
//输出到客户端
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(bi);
sos.flush();
}catch (Exception ex){
log.error("生成验证码失败!",ex);
}
}
4.CodeImageUtils
@Component
public class CodeImageUtils {
@Autowired
RedisTemplate redisTemplate;
/**
* 生成4位随机的验证码字符串
*
* @return
*/
public String getRandomCode() {
// 通过random生成4位随机数字码
Random random = new Random();
StringBuilder rs = new StringBuilder();
for (int i = 0; i < 4; i++) {
rs.append(random.nextInt(10));
}
return rs.toString();
}
/**
* 生成随机的颜色
*
* @return
*/
public Color getRandomColor() {
Random random = new Random();
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
/**
* 获取某颜色的反色
* @param color
* @return
*/
public Color getReverseColor(Color color) {
return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue());
}
/**
* 校验
* @param code
* @return
*/
public boolean valid(HttpServletRequest request,String code){
// 获取缓存的code
Object cacheCode = redisTemplate.opsForValue().get(request.getSession().getId());
if(cacheCode ==null){
return false;
}
return code.equals(cacheCode);
}
}
5.请求该接口
6.ImageIO
JPEGCodec这个在高版本的jdk中过期了,替换为ImageIO
//输出到客户端
ServletOutputStream sos = response.getOutputStream();
/*JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(bi);*/
ImageIO.write(bi, "PNG", sos);
sos.flush();
7.sessionId不一致
以上代码在单节点部署情况下暂时没发现什么问题,但是在多节点部署时会出现sessionId不一致的问题,(别问我怎么知道的…踩坑使我进步)。
解决方案为使用@EnableRedisHttpSession注解来开启session共享。
新增依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>2.1.12.RELEASE</version>
</dependency>
新增配置
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400)