Spring中整合Cage,實現驗證碼功能
阿新 • • 發佈:2018-03-19
ger 類型 body match exce sub pom esp rec
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"),這樣返回時將會以圖片形式,此處為坑。
Spring中整合Cage,實現驗證碼功能