首先导入ValidateCode.jar包
jar包的下载可以关注小宁博客公众号

实现类

public class ServletDemo4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //告诉客户端不使用缓存
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setIntHeader("expires", 0);
        
        
        ValidateCode vc = new ValidateCode(110, 25, 4, 9);
        String code = vc.getCode();//得到生成的字符
        vc.write(response.getOutputStream());
        
    }
}

网页代码

网页代码

<script type="text/javascript">
    function changeCode(){
        //得到图片元素
        var img = document.getElementsByTagName("img")[0];
        //img.setAttribute("src","/day09_00_HttpServletResponse/servlet/demo");//XML Dom 语法
        img.src = "/day09_00_HttpServletResponse/servlet/demo?time="+new Date().getTime();
    }
</script>
<img src="/day09_00_HttpServletResponse/servlet/demo4" onclick="changeCode()"/>
<a href="javascript:changeCode()" >看不清换一张</a>
Last modification:February 22, 2018
If you think my article is useful to you, please feel free to appreciate