生成验证码与点击事件切换验证码

验证码的生成和点击切换

hutool.jar(最重要jar包)

hutool.jar

JSP页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><script src="js/jquery-3.3.1.js"></script><script src="js/code.js"></script><style>div{margin: 0 auto;height: 200px;width: 50%;}label{font-size: 20px;}input{border-radius: 5px;margin-top: 25px;height: 50px;width: 200px;}img{margin-top: 50px;height: 100px;width: 200px;}</style>
</head>
<body>
<div><label  class="code">验证码:</label><input  type="text" class="form-control x164 in"><%--                src可以指向一个路径  也可以指向一个图片        --%><img id="codeImg" alt="点击更换" title="点击更换" src="/getCode" onclick="getCode()" class="m" >
</div>
</body>
</html>

code.js页面(页面的动态效果和点击事件)

 <script>//生成验证码// 流程://	1.点击图片 请求后台路径,将验证码的图片进行更换//  2.后台使用hutool工具类,生成图片验证码,并将验证码内容保存在session中function getCode(){// 浏览器都会有一个缓存//每毫秒都可以点击一次$("#codeImg").attr("src","/getCode?date="+new Date().getTime());//每一秒可以点击一次//   $("#codeImg").attr("src","/getCode?date="+new Date());}</script>

servlet文件(VerificationCode.java)

package verification.code;import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;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 java.io.IOException;/*** @author lotus* @description 验证码* @date 2021/1/20*/
@WebServlet("/getCode")
public class VerificationCode extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//         获取一个图片验证码//定义图形验证码的长、宽、验证码字符数、干扰元素个数CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
//        获取图片中的验证码内容String code = captcha.getCode();
//        把验证码存在session中req.getSession().setAttribute("code",code);
//        将图片验证码发送给前端captcha.write(resp.getOutputStream());}
}

效果图

如果仅生成验证码而不需要切换的话可以不用使用点击事件,仅需要servlet页面和jsp页面

本文链接:https://my.lmcjl.com/post/18639.html

展开阅读全文

4 评论

留下您的评论.