代码实现一个简单的生成随机验证码的小程序
	
	 
- //随机生成验证码
 - //第一步:
 - public void doGet(HttpServletRequest request, HttpServletResponse response)
 - throws ServletException, IOException {
 - test(response);
 - }
 - private void test(HttpServletResponse response) throws IOException {
 - int width = 120,height=25;
 - //生成一张图片 此时得到一张宽120,长25的一张黑色图片
 - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 - Graphics grap = img.getGraphics();//得到一个画笔
 - //填充背景色
 - grap.setColor(Color.pink);
 - //设置填充的区域
 - grap.fillRect(1, 1, width-2, height-2);
 - //设置边框的颜色 同填充背景颜色 靠近谁是设置哪个属性的颜色
 - grap.setColor(Color.red);
 - grap.drawRect(0, 0, width-1, height-1);
 - //设置字体
 - grap.setFont(new Font("黑体", Font.BOLD|Font.ITALIC, 18));
 - //向图片上写字 嘿嘿随机生成了字符串
 - Random r = new Random();
 - int p = 15;
 - for(int i=1;i<=4;i++)
 - {
 - grap.drawString(r.nextInt(10)+"", p,20);
 - p+=15;
 - }
 - //向图片上画线
 - for(int i=1;i<=10;i++)
 - {
 - grap.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
 - }
 - //把图片发送给客户端
 - ImageIO.write(img, "jpg", response.getOutputStream());
 - }
 - //第二部:新建login.html
 - <!DOCTYPE html>
 - <html>
 - <head>
 - <title>login.html</title>
 - <script type="text/javascript">
 - function ff(){
 - var img = document.getElementById("image");
 - img.src="/day33_response/demo4?user=1"+new Date().getTime();
 - // img.setAttribute("src","/day33_response/demo4?user="+new Date().getTime());
 - }
 - </script>
 - </head>
 - <body>
 - <form action="#" method="get">
 - 用户名<input type="text" name="uname"><br/><br/>
 - 密 码<input type="password" name="pwd"><br/><br/>
 - 验证码<input type="text" name="code">
 - <!-- 如果image没有写src页面刚加载时没有东西,刷新之后才会显示验证码图片 -->
 - <img id="image" src='/day33_response/demo4'>
 - <!-- 换两行 -->
 - <a href="javascript:ff()">换一张</a><br/> <br/>
 - <input type="submit" value="提交">
 - </form>
 - </body>
 - </html>
 - // 大功告成就可以发布到tomcat上浏览了
 - //此处介绍一种懒人方法,在doGet方法中,其中ValidateCode四个函数分别是矩形的宽、高以及验证码的个数和干扰线的条数,然后第一步的函数就可统统省略了
 - ValidateCode code = new ValidateCode(320, 25, 4, 8);
 - code.write(response.getOutputStream());
 - //注:导相应的ValidateCode的JAR包喔。
 
新闻热点
疑难解答