1.原理
使用Captcha用代码生成的验证码,然后把验证码的servlet通过图片标签的 src 属性 自动加载到浏览器中
2.步骤
1. 首先用Captcha绘图 把验证码图片给绘制出来
2. 把生成的验证码存放到 Session 会话当中,以供前台验证 填写验证码的准确性, 在构建文件路径,把验证码图片存入路径中
3. 前台返回路径
验证码生成代码:
package controller; import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.CircleCaptcha; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "LiuYanCodeServlet", urlPatterns = "/LiuYanCodeServlet") public class LiuYanCodeServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.定义图形验证码的宽、高、验证码字符数、干扰元素个数 CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 10); String code = captcha.getCode(); System.out.println(code); req.getSession().setAttribute("code",code);//把验证码存到session中 //2.把验证阿门输出到浏览器,利用response输出 //图形验证码写出,可以写出到文件,也可以写出到流 ServletOutputStream outputStream = resp.getOutputStream(); captcha.write(outputStream); outputStream.close(); } }
前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.4.1.js"></script> <!-- 引入 layui.css --> <link rel="stylesheet" href="layui/css/layui.css"> <!-- 引入 layui.js --> <script src="layui/layui.js"></script> </head> <body> <form class="layui-form" action="" onsubmit="return false"> <div class="layui-form-item"> <label class="layui-form-label">验证码:</label> <div class="layui-input-inline"> <input type="text" name="code" required lay-verify="required" placeholder="请输入验证码" autocomplete="off" class="layui-input"> </div> <div> <img src="/LiuYanCodeServlet" id="yzm" style="height: 37px;80px"> <span id="msg">点击图片刷新</span> </div> </div> </form> <script> layui.use(['form', 'carousel','jquery','layer'], function () { var form = layui.form; var carousel = layui.carousel; var $ = layui.jquery; var layer = layui.layer; $("#yzm").click(function (e) { $.ajax({ url:'/TBUserFlushCodeServlet', type: 'post', data:{ 'count':num }, success:function(res){ // console.log(res.toString());
//选中img标签,将属性设置为验证码路径。一定要加随机数,否则会认为请求相同不做处理
$("#yzm").attr("src","/LiuYanCodeServlet?"+time); // this.src = "/TBUserFlushCodeServlet?code="+new Date(); }, dataType: 'text', }); }); </script> </body> </html>
总结:
1.写一个servlet,生成随机验证码
2.利用ajax,重新对验证码的src属性赋值,赋值为生成验证码的servlet的urlPatterns 值