
文章插图
经过以上代码,我们的验证码生成功能基本上已经实现了,现在还需要一个controller来调用它 。
@ApiOperation(value = https://www.isolves.com/it/cxkf/kj/2020-09-02/"验证码")@GetMapping("/verifyCode")public void verifyCode(HttpServletRequest request, HttpServletResponse response) {IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();try {//设置长宽VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);String code = verifyCode.getCode();LOGGER.info(code);//将VerifyCode绑定sessionrequest.getSession().setAttribute("VerifyCode", code);//设置响应头response.setHeader("Pragma", "no-cache");//设置响应头response.setHeader("Cache-Control", "no-cache");//在代理服务器端防止缓冲response.setDateHeader("Expires", 0);//设置响应内容类型response.setContentType("image/jpeg");response.getOutputStream().write(verifyCode.getImgBytes());response.getOutputStream().flush();} catch (IOException e) {LOGGER.info("", e);}}
文章插图
搞定!后台编写到此结束了 。那么又会有博友说了:“说好的实现效果呢?”
好吧,那么我们继续前端的代码编写 。
前端代码:
<html><body><div><input id="code" placeholder="验证码" type="text" class=""style="width:170px"><!-- 验证码 显示 --><img οnclick="JavaScript:getvCode()" id="verifyimg" style="margin-left: 20px;"/></div><script type="text/javascript">getvCode();/*** 获取验证码* 将验证码写到login.html页面的id = verifyimg 的地方*/function getvCode() {document.getElementById("verifyimg").src = https://www.isolves.com/it/cxkf/kj/2020-09-02/timestamp("http://127.0.0.1:81/verifyCode");}//为url添加时间戳function timestamp(url) {var getTimestamp = new Date().getTime();if (url.indexOf("?") > -1) {url = url + "譼amp=" + getTimestamp} else {url = url + "?timestamp=" + getTimestamp}return url;};