1.pom.xml中添加Cage依赖。
<dependency>
<groupId>com.github.cage</groupId>
<artifactId>cage</artifactId>
<version>1.0</version>
</dependency>
项目相关资料:https://akiraly.github.io/cage/quickstart.html 。
2.Controller:@RestController
@RestController
@RequestMapping("captcha")
public class CaptchaController { @Autowired
private CaptchaService captchaService; @RequestMapping("get")
public void get(HttpServletResponse response,String key) throws IOException {
response.setContentType("image/jpeg");//设置响应的媒体类型,这样浏览器会识别出响应的是图片
response.getOutputStream().write(captchaService.getCaptcha(key));
response.flushBuffer();
}
}
3.Service:
@Service("captchaService")
public class CaptchaService { private static final Logger log = LoggerFactory.getLogger(CaptchaService.class); @Autowired
RedisDao redisDao;
Cage cage = new GCage(); public byte[] getCaptcha(String id) {
if (StringUtils.isBlank(id)) {
return null;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
String token = cage.getTokenGenerator().next().substring(0, 4);
try {
cage.draw(token, os);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
String key = "captcha-" + id;
redisDao.getJredis().opsForValue().set(key, token);
redisDao.getJredis().expire(key, 1, TimeUnit.HOURS);
return os.toByteArray();
} public boolean matchCaptcha(String id, String captcha) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(captcha)) {
return false;
}
String key = "captcha-" + id;
String redisCaptcha = String.valueOf(redisDao.getJredis().opsForValue().get(key));
if (StringUtils.isBlank(redisCaptcha)) {
return false;
}
log.info(id + ", " + captcha + ", " + redisCaptcha);
return StringUtils.equalsIgnoreCase(captcha, redisCaptcha);
}
}
4.前端页面:
$('#yzmimg').attr('src','https://localhost:8082/captcha/get?key'+timestamp);
总结:设置
response.setContentType("image/jpeg"),这样返回时将会以图片形式,此处为坑。