1.页面添加 一个验证码输入框 一个img标签用来存放验证码图
写一个imgCode()点击事件,用来刷新验证码
将获得的验证码放入redis缓存当中,登录的时候用来验证
验证图形验证码是否正确``
代码如下:
controller层:
@RequestMapping("toLogin")public String toLogin() {return "login";}@RequestMapping("login")public String login(User user, String code, Model model) {//判断验证码if (code == null || code.equals("")) {model.addAttribute("error", "请输入验证码");return "login";}String imgCode = (String) redisTemplate.opsForValue().get("imgCode");System.out.println(code + ";;;" + imgCode);if (!code.equals(imgCode)) {model.addAttribute("error", "验证码输入错误");return "login";}//判断用户是否存在User loginUser = userService.login(user);if (loginUser == null) {model.addAttribute("error", "用户名不存在");return "login";}//判断密码是否正确if (!loginUser.getPwd().equals(user.getPwd())) {model.addAttribute("error", "密码错误!!!");return "login";}return "list";}//图片验证码@RequestMapping("getImgCode")public void getImgCode(HttpServletResponse response) throws IOException {//定义图形验证码的长、宽、验证码字符数、干扰元素个数CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);//CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);//图形验证码写出,可以写出到文件,也可以写出到流//captcha.write("d:/circle.png");//验证图形验证码的有效性,返回boolean值captcha.verify("1234");captcha.write(response.getOutputStream());System.out.println("验证码:" + captcha.getCode());//验证码存入redisredisTemplate.opsForValue().set("imgCode", captcha.getCode(), 60, TimeUnit.SECONDS);}
dao层:
public interface UserDao {@Select("select * from `user` where name=#{name}")User login(User user);
}
jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="../../resource/bootstrap4/css/bootstrap.css"><script src="../../resource/js/jquery-3.2.1.js"></script><script src="../../resource/bootstrap4/js/bootstrap.js"></script><script src="../../resource/bootstrap-treeview/js/bootstrap-treeview.js"></script><title>$Title$</title>
</head>
<body>
<h1 style="color: #FF5722">${error}</h1>
<form method="post" action="/login">账号:<input name="name"><br><br>密码:<input name="pwd"><br><br>验证码:<input name="code"><img src="/getImgCode" width="60px" border="100px" id="img"><input type="button" value="点我刷新" onclick="imgCode()"><br><br><input type="submit" value="登录">
</form>
</body>
<script>function imgCode() {//若请求与前一次相等 则不提交请求 因此要写一个随机值$("#img").attr("src","/getImgCode?id="+Math.random());}
</script>
</html>