目录
- 引入Hutool
- 获得验证码图片 并把captcha写入session
- 前端请求接口得到验证码
- 后端处理得到的验证码
引入Hutool
<!-- hutool工具类--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.3</version></dependency>
获得验证码图片 并把captcha写入session
@GetMapping("/getImage")public String ImgCode() {LineCaptcha captcha = CaptchaUtil.createLineCaptcha(150, 50, 4, 6);ByteArrayInputStream imageStream = new ByteArrayInputStream(captcha.getImageBytes());WebUtils.getSession().setAttribute("cap", captcha);ServletOutputStream outputStream = null;try {outputStream = WebUtils.getResponse().getOutputStream();} catch (IOException e) {e.printStackTrace();}captcha.write(outputStream);return null;}
前端请求接口得到验证码
<div class="layui-form-item input-item" id="imgCode"><label for="code">验证码</label><input type="text" placeholder="请输入验证码" autocomplete="off" id="code" class="layui-input" style="width: 60%;" name="vername"><img src="/login/getImage" style="width:100px;height:40px"></div>
后端处理得到的验证码
@PostMapping("/login")
public Result login(String loginname, String pwd,String vername){LineCaptcha captcha = (LineCaptcha)WebUtils.getSession().getAttribute("cap");boolean verify = captcha.verify(vername);if(!verify)return Result.LOGIN_ERROR_VERIFY;...
}