程序员的资源宝库

网站首页 > gitee 正文

Hutoll 图文验证Demo

sanyeah 2024-04-12 17:42:16 gitee 8 ℃ 0 评论

我采用的是Spring boot 

1:pom.xml依赖

       <!-- Hutool 依赖-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.5</version>
        </dependency>

  

2:前端页面:

<img src="/getImage?count=0" id="authCodeImg" onclick="changeCodeImg(this)"><!--显示的验证码-->
<input type="text" id="name1" class="form-control" placeholder="请输入验证码" aria-describedby="basic-addon2">
<!--验证验证码-->

3:前端ajax请求:

//<!-- 图文验证码验证-->
    $('#name1').blur(function () {
        $.ajax({
            url: "/getverfy",
            type: "post",
            data: {
                vername:$("#name1").val()
            },
            success: function (result) {
                if(result=="图文验证成功")
                {

                }else{
                    alert("图文验证失败!")
                    location.reload();
                }
            }
        })
    })

//图文验证码
$.ajax({
url: "/getImage",
type: "post",
data: {

},
success: function (result) {
result.src = "/getImage?count=1&timestamp="+new Date().getTime();
}
})

 controller:

/**
     * 生成图片验证码
     * @param request
     * @param response
     */
    @RequestMapping("getImage")
    public void ImgCode(HttpServletRequest request, HttpServletResponse response) {
       LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        try {
            request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
            response.setContentType("image/png");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            lineCaptcha.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对验证码进行输入验证
     * @param vername
     * @return
     */
    @RequestMapping("getverfy")
    public @ResponseBody String verfy(String vername) {

        if (lineCaptcha.verify(vername)) {
            return "图文验证成功";
        }
        return "图文验证失败";
    }

  

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表