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

2 篇文章 0 订阅

验证码的生成和点击切换

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 {
    @Override
    protected 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页面

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值