重点可以查看Hutool — 🍬A set of tools that keep Java sweet.
的参考文档。
1.导入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.5</version>
</dependency>
2.登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="bp" value="${pageContext.request.contextPath}" scope="session"/>
<html>
<head>
<title>登录页</title>
<link rel="stylesheet" type="text/css" href="${bp}/static/css/base.css">
<script src="${bp}/static/js/jquery-1.11.1.js"></script>
</head>
<body>
<div id="login">
<h3>欢迎登录</h3>
<form action="${bp}/user?method=login" method="post">
<p><input type="text" name="username" class="input" placeholder="请输入用户名"></p>
<p><input type="password" name="password" class="input" placeholder="请输入密码"></p>
<p><input type="text" name="token" style="width: 200px;height: 50px; margin-right: 10px" placeholder="请输入验证码"><img src="${bp}/user?method=getCode" width="90px" height="50px"style="vertical-align: middle" onclick="changeImg()"></p>
<p><input type="submit" value="立即登录" class="input"><a href="register.jsp">注册账号</a></p>
</form>
<%-- 显示登录错误的信息--%>
<span style="color: red">${requestScope.msg}</span>
</div>
<script>
//单击改变验证码
function changeImg() {
let sr = $("img").attr("src")+"&date= "+new Date().getTime()
$("img").attr("src",sr)
}
</script>
</body>
</html>
重点部分:
<p><input type="text" name="token" style="width: 200px;height: 50px; margin-right: 10px" placeholder="请输入验证码"><img src="${bp}/user?method=getCode" width="90px" height="50px"style="vertical-align: middle" onclick="changeImg()"></p>
<script>
//单击改变验证码
function changeImg() {
let sr = $("img").attr("src")+"&date= "+new Date().getTime()
$("img").attr("src",sr)
}
</script>
</body>
</html>
3.servlet部分
// 生成验证码
protected void getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
// 包含干扰线的验证码图片 width 图片宽度 height:图片高度 codeCount 验证码的位数 lineCount 干扰线的条数
LineCaptcha lineCaptcha = new LineCaptcha(100, 60, 4, 5);
// 获取图片中的验证码 保存在session会话对象中 用于后续登录验证
String code = lineCaptcha.getCode();
System.out.println("code = " + code);
req.getSession().setAttribute("code", code);
//将图片以流的形式响应给前端浏览器
ServletOutputStream outputStream = resp.getOutputStream();
lineCaptcha.write(outputStream);
outputStream.close();
}