java实现网页计数器功能_用 img 标签 实现 网页计数器

1 importjava.awt.Color;2 importjava.awt.Font;3 importjava.awt.Graphics;4 importjava.awt.image.BufferedImage;5 importjava.io.ByteArrayOutputStream;6 importjava.io.FileInputStream;7 importjava.io.FileOutputStream;8 importjava.io.IOException;9 importjava.util.Properties;10 11 importjavax.imageio.ImageIO;12 importjavax.servlet.ServletException;13 importjavax.servlet.ServletOutputStream;14 importjavax.servlet.http.HttpServlet;15 importjavax.servlet.http.HttpServletRequest;16 importjavax.servlet.http.HttpServletResponse;17 18 publicclassCountServletextendsHttpServlet {19 20 privatestaticfinallongserialVersionUID=1L;21 22 publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)23 throwsServletException, IOException {24 response.setContentType("image/jpeg");25 //设置浏览器不要缓存此图片26 response.setHeader("Pragma","No-cache");27 response.setHeader("Cache-Control","no-cache");28 response.setDateHeader("Expires",0);29 30 ServletOutputStream sos=response.getOutputStream();31 32 BufferedImage image=newBufferedImage(80,20,33 BufferedImage.TYPE_INT_RGB);34 Graphics g=image.getGraphics();35 36 g.setColor(Color.WHITE);37 g.setFont(newFont(null, Font.ITALIC|Font.BOLD,18));38 String value=getAccessCount(request);39 intlen=value.length();40 //最大访问次数不超过999999941 if(len>7) {42 value="9999999";43 }else{44 String tmp="";45 for(inti=0; i<7-len; i++) {46 tmp=tmp+"0";47 }48 value=tmp+value;49 }50 g.drawString(value,0,18);51 //结束图像的绘制过程,完成图像52 g.dispose();53 //避免因图像大小超过Servlet引擎输出缓冲区的大小而自动使用chunked编码54 ByteArrayOutputStream bos=newByteArrayOutputStream();55 ImageIO.write(image,"JPEG", bos);56 byte[] buf=bos.toByteArray();57 response.setContentLength(buf.length);58 bos.close();59 sos.write(buf);60 sos.close();61 }62 63 privateString getAccessCount(HttpServletRequest request) {64 //得到引用页面的URL地址,并以此作为访问次数的检索关键字65 String pageKey=request.getHeader("referer");66 if(pageKey==null) {67 return"0";68 }69 70 Properties settings=newProperties();71 String countFilePath=getServletContext().getRealPath("/count.txt");72 try{73 FileInputStream fi=newFileInputStream(countFilePath);74 settings.load(fi);75 fi.close();76 }catch(Exception e) {77 e.printStackTrace();78 }79 String count="0";80 try{81 count=settings.getProperty(pageKey);82 if(count==null) {83 count="0";84 }85 intc=Integer.parseInt(count)+1;86 count=newInteger(c).toString();87 settings.put(pageKey, count);88 FileOutputStream fi=newFileOutputStream(countFilePath);89 settings.store(fi,"the page is accessed:");90 fi.close();91 }catch(Exception e) {92 e.printStackTrace();93 }94 returncount;95 }96 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值