登录功能的验证码实现
Controller:
public class SysLoginController extends AbstractController { @Autowired private SysCaptchaService sysCaptchaService; /** * 验证码 */ @GetMapping("captcha.jpg") public void captcha(HttpServletResponse response, String uuid)throws IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); //获取图片验证码 BufferedImage image = sysCaptchaService.getCaptcha(uuid); ServletOutputStream out = response.getOutputStream(); //ImageIO 類別的 write() 接受一個 OutputStream 物件,可以將你指定的 BufferedImage 寫入至指定的 OutputStream ImageIO.write(image, "jpg", out); //优雅的关闭流,只不过commom-io在2.6版本之后,就不使用了(也是jdk7以前) IOUtils.closeQuietly(out); } }
SysCaptchaServiceImpl:
/** * 验证码 * @author */ @Service("sysCaptchaService") public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptchaEntity> implements SysCaptchaService { @Autowired private Producer producer; @Override public BufferedImage getCaptcha(String uuid) { if(StringUtils.isBlank(uuid)){ throw new RRException("uuid不能为空"); } //生成文字验证码 String code = producer.createText(); SysCaptchaEntity captchaEntity = new SysCaptchaEntity(); captchaEntity.setUuid(uuid); captchaEntity.setCode(code); //5分钟后过期 captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5)); this.save(captchaEntity); // System.out.println(captchaEntity); //做成的图片大小和样式可以控制吗?还是默认的? return producer.createImage(code); } //登录时验证 @Override public boolean validate(String uuid, String code) { SysCaptchaEntity captchaEntity = this.getOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", uuid)); if(captchaEntity == null){ return false; } //删除验证码 this.removeById(uuid); if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){ return true; } return false; } }
一个小小后端的爬行痕迹