java 生成验证码图片 ValidateCode 显示到页面img控件

耗尽温柔 提交于 2020-02-10 23:01:33

 ValidateCode.jar :https://mp.csdn.net/postedit/100535977

 

 

springmvc  后端

@Controller
public class User {

    @RequestMapping("index")
    public void captcharBuild(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //生成验证码
        //1.创建验证码对象
        /*
         * ValidateCode
         * 1.宽度
         * 2.高度
         * 3.验证码个数
         * 4.干扰线条数
         */
        ValidateCode code = new ValidateCode(200, 30, 4, 6);
        code.getCode();   //获取验证码
        //2。获取response对象
        code.write(response.getOutputStream());
    }

}

 

前端

<html>

<body>

<img id="imageDis" src=""/>
<button id="but" >更换图片</button>


</body>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script type="text/javascript">
    document.getElementById("but").onclick=function(){
        document.getElementById('imageDis').src="index?"+Math.random();   //index是请求路径
    }
</script>
</html>

看到这里有人可能要问,src请求路径,后面为什么要加随机数参数,应为你重复访问一个url  浏览器会调用缓存,也就说,无论你怎么更换图片,他永远都显示第一张图片,应为后面的请求不会生效。所以在后面加一个随机数,保证每次的请求url不一样,每次都去请求生成新的图片

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!