Cookie
1.是服务器发送到浏览器,并保存在浏览器端的一小块数据
2.浏览器下次访问该服务器时,会自动携带该数据,将其发送给服务器
Session
1.是JavaEE的标准,用于在服务端记录客户端的信息
2.数据存放在服务端更加安全,但是也会增加服务端的内存压力
生成验证码
Kaptcha
1.导入jar包
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
2.编写Kaptcha配置类
这个了解就好了,有需要的时候再过来看,不用记
@Configuration public class KaptchaConfig { @Bean public Producer kaptchaProducer() { Properties properties = new Properties(); properties.setProperty("kaptcha.image.width","100"); properties.setProperty("kaptcha.image.height","40"); properties.setProperty("kaptcha.textproducer.font.size","32"); properties.setProperty("kaptcha.textproducer.font.color","0,0,0"); properties.setProperty("kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKMNPQRSTUVWXYZ"); properties.setProperty("kaptcha.textproducer.char.length","3"); properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise"); DefaultKaptcha kaptcha = new DefaultKaptcha(); Config config = new Config(properties); kaptcha.setConfig(config); return kaptcha; } }
3.生成随机字符、生成图片
@RequestMapping(value = "/kaptcha", method = RequestMethod.GET) public void getKaptcha(HttpServletResponse response /*HttpSession session*/) { //生成验证码 //此前已经将Producer注入到Spring容器里了 String text = kaptchaProducer.createText(); BufferedImage image = kaptchaProducer.createImage(text); // Ed---0.1 // 将验证码存入session // session.setAttribute("kaptcha", text); //Ed---0.2 //设置验证码的归属 String kaptchaOwner = CommunityUtil.generateUUID(); Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner); cookie.setMaxAge(60); cookie.setPath(contextPath); response.addCookie(cookie); //将验证码存入Redis String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner); redisTemplate.opsForValue().set(kaptchaKey, text, 60, TimeUnit.SECONDS); //将图片输出给浏览器 response.setContentType("image/png"); ServletOutputStream os = null; try { os = response.getOutputStream(); ImageIO.write(image, "png", os); } catch (IOException e) { logger.error("相应验证码失败" + e.getMessage()); } }
前端页面,每次点击刷新验证码,触发js响应
<div class="form-group row mt-4"> <label for="verifycode" class="col-sm-2 col-form-label text-right">验证码:</label> <div class="col-sm-6"> <input type="text" th:class="|form-control ${codeMsg!=null?'is-invalid':''}|" id="verifycode" name="code" placeholder="请输入验证码!"> <div class="invalid-feedback" th:text="${codeMsg}"> 验证码不正确! </div> </div> <div class="col-sm-4"> <img th:src="@{/kaptcha} " id="kaptcha" style="width:100px;height:40px;" class="mr-2"/> <a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a> </div> </div>
<script> function refresh_kaptcha() { var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random(); $("#kaptcha").attr("src",path); } </script>