成果图:
要完成这个验证码功能需要有导入一个jar包,
;
我们要新建一个后端类用来验证码的生成:
package fangwuzulin.yewu;
import cn.dsna.util.images.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/code")
public class code extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建了一个 ValidateCode 实例,传入四个参数:
//第一个参数是验证码图像的宽度(500 像素)。
//第二个参数是验证码图像的高度(200 像素)。
//第三个参数是验证码字符的数量(4 个字符)。
//第四个参数是干扰线的数量(100 条线)。
ValidateCode validateCode = new ValidateCode(500,200,4,100);
//拿到生成的验证码值
String code = validateCode.getCode();
//将生成的验证码字符串存储到 session 中,键为 "code"
// 这样可以在后续的请求中验证用户输入的验证码是否正确
HttpSession sessions = req.getSession();
sessions.setAttribute("code",code);
//将生成的验证码图像写入到响应的输出流中。
// 验证码图像会被发送给客户端显示。
validateCode.write(resp.getOutputStream());
}
}
现在后端就生成了验证码的图片和数据,现在我们要把验证码放到前端显示:
这是前端的主体:
<body>
<div>
<h1>欢迎登录</h1>
<form action="denglu" method="get">
<label for="user">账号:</label>
<input type="text" id="user" name="user" required>
<label for="pwd">密码:</label>
<input type="password" id="pwd" name="pwd" required>
<img src="code" alt="加载失败" width="100" onclick="this.src=this.src+'?'+Math.random()">
<input type="text" ID="yz" name="yz">
<button type="button" onclick="denglu()">登录</button>
<button type="button" >注册</button>
</form>
</div>
</body>
关于验证码最重要的就是这一行:
<img src="code" alt="加载失败" width="100" onclick="this.src=this.src+'?'+Math.random()">
<img>
: 这是 HTML 中的图像标签,用于在网页上展示图片。src="code"
:src
属性指定了图像的源文件位置。在这里,"code"
可能是指向服务器端的一个脚本(例如 PHP 或者 Java Servlet),该脚本负责生成验证码图片并返回给客户端。通常情况下,这会是一个动态生成的图片。alt="验证码加载失败"
:alt
属性提供了当图像无法显示时的一个替代文本。这里设置为 "验证码加载失败",意味着当验证码图像无法加载时,浏览器会显示这句话。width="100"
:width
属性指定了图像的宽度,这里是 100 像素。onclick="this.src=this.src+'?'+Math.random()"
:onclick
属性定义了当用户点击该图像时触发的 JavaScript 代码。这段代码的作用是在点击图像时更新图像的src
属性,从而刷新验证码。this.src = this.src + '?' + Math.random();
: 更新src
属性,使其包含原来的 URL 加上随机数,这样就会请求一个新的验证码图像。
这样我们的验证码就显示在前端页面了,最后我们再加上比对的逻辑让验证码在正确时进入正确的页面,在错误时弹框告知。
在js中:
const yzInput = document.getElementById('yz');
通过这个方式拿到验证框里用户输入的值,
const user = {
user: name,
pwd: pwd,
yz:yz
};
将值放入对象里,再用post方式传到后端:
//将对象JSON序列化
let s = JSON.stringify(user);
//配置向后端请求类型 get post 异步请求数据 传递数据
xmlHttpRequest.open("post", "/ajax_war_exploded/denglu" , true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
//将值传回后端
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.send(s);
这样我们就将验证码的值传回了后端,我们只要在后端将验证码比对就能知道是否正确。