目录

Hutool生成的验证码展示在前端,点击刷新实例

目录

Hutool生成的验证码展示在前端,点击刷新实例

这个实例还遇到个有意思的问题,废话不多说,先放前端代码

<img src="/register/getAuthCodeImg?count=0" id="authCodeImg" onclick="changeCodeImg(this)">

src是我请求后台的路径

JS代码:

 function changeCodeImg(codeImg){
				 codeImg.src = "/register/getAuthCodeImg?count=1&timestamp="+new Date().getTime();
			 }

这里就是那个有意思的问题了,刚开始我没加timestamp,点击验证码刷新的时候只能触发一次,后来了解到 在URL中加时间戳就会保证每一次发起的请求都是一个不同于之前的请求,这样就能避免浏览器对URL的缓存。

URL后面添加随机数通常用于防止客户端(浏览器)缓存页面。 浏览器缓存是基于url进行缓存的,如果页面允许缓存,则在一定时间内(缓存时效时间前)再次访问相同的URL,浏览器就不会再次发送请求到服务器端,而是直接从缓存中获取指定资源。

Controller

 /**
     * 获取验证码图片
     * @return
     */
    @RequestMapping("/getAuthCodeImg")
    public void  getAuthCodeImg(HttpSession session, HttpServletResponse response, Integer count){

        //定义图形验证码的长和宽  码值个数  干扰圈数
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(90, 40, 4, 10);
        BufferedImage codeImg = circleCaptcha.getImage();

       if (null != count && count > 0){
            //重新生成验证码
            circleCaptcha.createCode();
        }
        //String codeImg = lineCaptcha.getImageBase64();
        String authCode = circleCaptcha.getCode();
        if(session.getAttribute("validateCode")!=null){
            session.removeAttribute("validateCode");
            session.setAttribute("validateCode", authCode);
        }else{
            session.setAttribute("validateCode", "请输入验证码");
        }
        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            ImageIO.write(codeImg, "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

不要忘了在pom.xml中添加依赖

<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.0.7</version>
        </dependency>