用Java Servlet构建旗帜广告系统

作者:网络 来源:佚名 更新时间:2008-11-17 15:22:52 点击:

  对于一个商务网站来说,广告系统是必不可少的。一个好的广告系统是一个网站稳定收入的基础。而旗帜广告(banner)则是网站广告中占绝大部分的广告,因此开发一个旗帜广告系统就非常重要了。利用java servlet 我们可以很轻松的构建属于我们自己的旗帜广告系统。

  我们一般在网页上放上一些图片,设置它们的链接指向广告客户的网页,然后产生日志文件存放浏览的人数,浏览者的ip等信息,这就是开发旗帜广告系统的一般思路。

  下面,我想结合一个例程来介绍一下如何使用java servlet来构建旗帜广告系统。这下面这个例子中,你必须使用在你的html文件中使用<img> 标签。

  用法有三种是:

  1) banner?config_file 或banner?config=config_file

  例如:

  <img height=125 src="http://localhost/servlet/banner?config_file" width=125>

  用这种方法你就可以显示不同的图片了。

  2) 你也可以为每一幅图片设置自己的重定向url。只需在你的设置中添加文件描述,见下面的例子,servlet也需要更多的描述参数:

  <img height=60 src="http://localhost/servlet/banner?config=config_file&mode=1" width=468>

  这样你就可以支持标准的旗帜广告了。

  3)你也可以在同一个页面上有多个旗帜广告。你只需要在参数中加入“id=某个整数值”就可以了。这个值必须是一个你的页面内唯一的整数值!例如,对于第一个banner的描述为:

  <img height=60 src="http://localhost/servlet/banner?config=config_file&mode=1&id=1" width=468>

  第二个为:

  <img height=125 src="http://localhost/servlet/banner?config=config_file&mode=1&id=2" width=125>


|||

  有的朋友会问了,config_file是什么文件呀? 它是一个文本文件,用来描述servlet的设置信息。你能在你的主机的任何地方保存这个文件。现把参数介绍一下,这个配置文件有三个参数:分别为

  1、dir=some_directory

  解释: dir是你的旗帜广告文件存放的目录,可以使用的图片格式有jpg ,gif,png ,jpeg等。这个参数是必须有的,否则系统会报错。

  2、bannerfilename=some_url

  解释: banner文件使用下面的格式,例如:

   banner.gif=http://www.ddvip.com/

  banner.jpg=http://www.ddvip.com/

  3、log=some_directory_to_store_log_file

  解释:存放日志文件的目录,可以是服务器上的任何目录。

  附录1、日志文件(log file)及格式

  banner 系统每天会自动产生两个日志文件。分别为ddmmyyyyv.txt和ddmmyyyyc.txt 。第一个文件保存浏览banner的记录,第二个文件保存重定向的记录。两个文件都是文本文件,每一行包括一条记录。纪录格式是:

  ip地址 日期 图片文件 用户代理 重定向记录 (只用于 *c.txt文件) ,字段之间用空格隔开。

  附录2、banner.java源程序:

  import java.io.*;
   import java.util.*;
   import javax.servlet.*;
   import javax.servlet.http.*;
   public class banner extends httpservlet
    {
     public banner(){ }
     file://读取配置文件内容
     private boolean readconfig(string sconfig, hashtable hashtable)
     {
      try
       {
        bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(new fileinputstream(sconfig)));// 设置缓冲区读入一个配置文件
        string slineinformation1;//
        while((slineinformation1 = bufferedreader.readline()) != null)
        {
         slineinformation1 = slineinformation1.trim();//去除字符串中的空格
         if(slineinformation1.length() > 0)//如果字符串slineinformation1的长度大于零 {
          int i = slineinformation1.indexof("=");
          if(i > 0 && i < slineinformation1.length() - 1 && slineinformation1.charat(0) != '#' && !slineinformation1.startswith("//"))//配置文件的每一行参数必须以不为#或//开头的字符串
           hashtable.put(slineinformation1.substring(0, i).trim().tolowercase(), slineinformation1.substring(i + 1).trim());
           }
          }
         bufferedreader.close();
         file file = new file(sconfig);//创建一个配置文件
         hashtable.put("edited", string.valueof(file.lastmodified()));
         }
        catch(exception _ex)
        {
         return false;
        }
       string sdirinfo2 = (string)hashtable.get("dir");//取得目录参数
       if(sdirinfo2 != null)//如果目录参数是空值
        {
         if(!sdirinfo2.endswith(separator))//如果sdirinfo2不是以分隔符结尾,那么
         {
          sdirinfo2 = sdirinfo2 + separator;//给sdirinfo2加上分隔符
          hashtable.remove("dir");//移去哈希表变量中的dir
          hashtable.put("dir", sdirinfo2);
         }
       file file1 = new file(sdirinfo2);
       string as[] = file1.list();
       if(as == null) {
        hashtable.remove("dir");
        }
       sdirinfo2 = (string)hashtable.get("log");
       if(sdirinfo2 != null)
        {
         if(!sdirinfo2.endswith(separator))
          {
           sdirinfo2 = sdirinfo2 + separator;
           hashtable.remove("log");
           hashtable.put("log", sdirinfo2);
          }
       file file2 = new file(sdirinfo2);
       string as1[] = file2.list();
       if(as1 == null) {
        hashtable.remove("log");
        }
       return true;
      }
     private hashtable getconfig(string s)//取得配置
      {
       hashtable hashtable = (hashtable)cfgs.get(s);
       if(hashtable != null)//如果配置不为空
       try
        {
         string s1 = (string)hashtable.get("edited");
         file file = new file(s);
         if(!s1.equals(string.valueof(file.lastmodified()))){
         file://如果s1的值不等于文件最后一次修改的值,则hashtable的内容为空值
          hashtable = null;
          }
         catch(exception _ex)//捕获exception _ex错误
          {
           hashtable = null;
          }
         if(hashtable != null)
          return hashtable;
          hashtable = new hashtable();
         if(!readconfig(s, hashtable))
          {
           return null;
          }
         else
          {
           cfgs.put(s, hashtable);
           return hashtable;
          }
         }
      public void init(servletconfig servletconfig)//初始化配置参数
       throws servletexception {
         file://如果出错,抛出一个servletexception错误
          super.init(servletconfig);
          separator = system.getproperty("file.separator");//取得分隔符
          cfgs = new hashtable();//设置配置变量
          logs = new hashtable();//设置日志变量
          system.out.println("©wayne zheng");//屏幕输出我的邮箱地址
         }
      public void destroy()
      {
       }
      public void dopost(httpservletrequest request, httpservletresponse response)
       file://发送post请求
       throws servletexception, ioexception
        { doget(request, response); }
       public void doget(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse) file://读取get
       throws servletexception, ioexception
       {
        string strconfig = httpservletrequest.getquerystring();
        file://读取请求字符串
        if(strconfig == null)//如果字符串为空
         strconfig = "";//那么设置strconfig为空
         if(strconfig.length() == 0)
         file://如果strconfig长度为零,那么显示错误信息
         {
          errormessage("无配置信息!", httpservletresponse);
          return;
         }
         string strconfig1 = getfromquery(s, "config=");//同上
         if(strconfig1.length() == 0){
          strconfig1 = strconfig;
          hashtable hashtable = getconfig(strconfig1);
          if(hashtable == null)
          {
            errormessage("配置信息错误!", httpservletresponse);
            return;
          }
          if(hashtable.get("dir") == null)
          file://如果哈希表中dir为空值,则输出错误信息
          {
           errormessage("不能打开数据目录", httpservletresponse);
           return;
          }
        string strconfigmode2 = getfromquery(strconfig, "mode=");//读取配置中的mode值
        if(strconfigmode2.length() == 0){//如果没有mode值
         strconfigmode2 = "1";//则设mode值为1
         string strconfigid3 = getfromquery(strconfig, "id=");//读取配置中的id值
         if(strconfigid3.length() == 0){ file://如果没有id值
           strconfigid3 = "1";//则设id值为1
           httpsession httpsession = httpservletrequest.getsession(true);
           if(strconfigmode2.equals("1"))
           file://如果strconfigmode2的值为1,则显示banner广告
           {
            showbanner(hashtable, strconfigid3, httpsession, httpservletrequest, httpservletresponse);
            return;
            }
           else file://否则转向banner所指的站点
            {
             gotosite(hashtable, strconfigid3, httpsession, httpservletrequest, httpservletresponse);
             return;
            }
          }
        private void gotosite(hashtable hashtable, string s, httpsession httpsession, httpservletrequest httpservletrequest, httpservletresponse httpservletresponse)//转向站点
         throws ioexception file://如果有任何错误,抛出ioexception错误
         {
          string sitename1;//定义站点名
          if(httpsession == null)//如果httpsession为空
           {
            sitename1 = getfirstsite(hashtable);//站点名为哈希表中的第一个站点名
            }
          else file://否则
           {
            hashtable hashtable1 = (hashtable)httpsession.getvalue("旗帜广告系统 ,wayne zheng");
          if(hashtable1 == null){ file://如果哈希表hashtable1为空值,则
            sitename1 = getfirstsite(hashtable);// 站点名为哈希表(hashtable)中的第一个站点名
          else
            sitename1 = (string)hashtable1.get(s);
          }
         if(sitename1 == null)
         file://如果站点名为空值则站点名为默认值http://www.yesky.com
         sitename1 = "http://www.yesky.com";
         string s2;
         if(hashtable.get("log") != null && (s2 = getfilebyurl(hashtable, s1)) != null){
          writelog(hashtable, s2, sitename1, "c", httpservletrequest);
          httpservletresponse.sendredirect(sitename1);
          }
     private void showbanner(hashtable hashtable, string s, httpsession httpsession, httpservletrequest httpservletrequest, httpservletresponse httpservletresponse)
     throws ioexception
     {
      string s1 = (string)hashtable.get("dir");
      file file = new file(s1);
      vector vector;
      if(file == null)
       {
        vector = new vector();
       }
      else
       {
        string as[] = file.list();
        vector = getgraphfiles(as);
       }
      if(vector.size() == 0)
       {
        httpservletresponse.setcontenttype("text/html");
        printwriter out = httpservletresponse.getwriter();
        out.println("目录是空的!");
        out.flush();
 
        out.close();
        return;
       }
      int i;
      if(httpsession != null)
       synchronized(hashtable.get("dir"))
       {
        integer integer;
        int j;
        if((integer = (integer)httpsession.getvalue("bi")) == null){
         j = 0;
        else
         j = integer.intvalue();
         if(j >= vector.size()) {
          j = 0;
          i = j;
          if(++j >= 3){
           j = 0;
           httpsession.putvalue("bi", new integer(j));
          }
          else
            i = 0;
            string s2 = (string)vector.elementat(i);
            string s3;
            if(httpsession != null && (s3 = geturl(hashtable, s2)) != null)
             {
              hashtable hashtable1;
              if((hashtable1 = (hashtable)httpsession.getvalue("旗帜广告系统 ,wayne zheng")) == null){
               hashtable1 = new hashtable();
               hashtable1.put(s, s3);
               httpsession.putvalue("旗帜广告系统 ,wayne zheng", hashtable1);
               }
              if(hashtable.get("log") != null) {
               writelog(hashtable, s2, "v", httpservletrequest);
               outputbanner(s2, hashtable, httpservletresponse);
               vector = null;
               }
     private void writelog(hashtable loghashtable, string logstring, string logstring1, string logstring2, httpservletrequest httpservletrequest)//写日志的函数
     {
      string logstring3 = (string)hashtable.get("log");
      string logstring4 = getlogstring(logstring, httpservletrequest) + " "" + logstring1 + """;
      gregoriancalendar gregoriancalendar = new gregoriancalendar();
      file://获取当前的时间
      gregoriancalendar.settime(new date());
      string logstring5 = logstring3 + stringdate(gregoriancalendar) + logstring2 + ".txt";//以时间戳和“c”或“v”为文件名来写日志文件
      savelog(hashtable, logstring5, logstring4);
      }
      private void writelog(hashtable loghashtable, string logstring, string logstring1, httpservletrequest httpservletrequest) file://写日志文件
      {
       string logstring2 = (string)loghashtable.get("log");
       string logstring3 = getlogstring(logstring, httpservletrequest);
       gregoriancalendar gregoriancalendar = new gregoriancalendar();
       gregoriancalendar.settime(new date());
       string logstring4 = logstring2 + stringdate(gregoriancalendar) + logstring1 + ".txt";
       savelog(loghashtable, logstring4, logstring3);
      }
     private void savelog(hashtable hashtable, string s, string s1)//把日志文件保存在硬盘上
      {
        synchronized(hashtable.get("log"))
       {
        try
         {
          filewriter filewriter = new filewriter(s, true);
          printwriter printwriter = new printwriter(filewriter);
          printwriter.println(s1);
          printwriter.flush();
          printwriter.close();
          filewriter.close();
         }
        catch(exception _ex) { }
      }
     }
    private string getlogstring(string s, httpservletrequest httpservletrequest)
    file://取得日志字符串
     {
      string s1 = httpservletrequest.getremoteaddr();
      file://取得远程的访问者的ip地址
      string s2 = httpservletrequest.getheader("user-agent");
      string s3 = httpservletrequest.getheader("referer");
      string s4 = """ + s + """;
      if(s1 == null)
       s1 = "-";
       if(s2 == null)
        s2 = "-";
       else
        s2 = """ + s2 + """;
       if(s3 == null)
        s3 = "-";
       else
        s3 = """ + s3 + """;
       return s1 + " [" + new date() + "] " + s4 + " " + s3 + " " + s2;
      }
    private string stringdate(calendar calendar) file://取得时间戳
     {
       string s = string.valueof(calendar.get(1));
       string s1 = string.valueof(calendar.get(2));
       if(s1.length() == 1)
         s1 = "0" + s1;
         s = s + s1;
         s1 = string.valueof(calendar.get(5));
         if(s1.length() == 1)
          s1 = "0" + s1;
          return s + s1;
        }
     private string getfilebyurl(hashtable hashtable, string s)
      {
       for(enumeration enumeration = hashtable.keys(); enumeration.hasmoreelements();)
        file://hashtable的keys()方法返回了哈希表关键字的枚举,enumeration的hasmoreelements()方法测试枚举重是否还有其他元素
        {
         string s1 = (string)enumeration.nextelement();
         file://让s1的值为enumeration的下一个元素值
         if(s.equals(hashtable.get(s1)))//如果s的值为s1的值,则
          return s1;//返回s1的值
        }
        return null;
       }
     private string getfirstsite(hashtable hashtable)//取得第一个站点的名字
      {
       string s = (string)hashtable.get("dir");
       file file = new file(s);
       if(file == null)
         return null;
         string as[] = file.list();
         vector vector = getgraphfiles(as);
         file://设置vector向量变量来获取图形文件
         if(vector.size() == 0)//如果没有图形文件,则返回空值
           return null;
         else
           return geturl(hashtable, (string)vector.elementat(0));
         }
     private string geturl(hashtable hashtable, string s)//取得url
      {
        string s1 = s.tolowercase();//设置s1为s的小写形式
        for(enumeration enumeration = hashtable.keys(); enumeration.hasmoreelements();)
        {
         string s2 = (string)enumeration.nextelement();
         if(s1.equals(s2.tolowercase()))
          return (string)hashtable.get(s2);
        }
       return null;
     }
    private void outputbanner(string s, hashtable hashtable, httpservletresponse httpservletresponse)//输出banner广告
     throws ioexception//如果有错则抛出ioexception错误
     {
      string s1 = (string)hashtable.get("dir") + s;
      httpservletresponse.setheader("cache-control", "no-store");
      httpservletresponse.setheader("pragma", "no-cache");
      httpservletresponse.setdateheader("expires", 1l);
      httpservletresponse.setcontenttype("image/" + s.substring(s.indexof(".") + 1));
      javax.servlet.servletoutputstream servletoutputstream = httpservletresponse.getoutputstream();
      dumpfile(s1, servletoutputstream);
      servletoutputstream.flush();
      servletoutputstream.close();
      }
     private boolean dumpfile(string s, outputstream outputstream)
      {
       byte abyte0[] = new byte[4096];
       boolean flag = true;
       try
        {
         fileinputstream fileinputstream = new fileinputstream(s);
         int i;
         while((i = fileinputstream.read(abyte0)) != -1)
          outputstream.write(abyte0, 0, i);
          fileinputstream.close();
          }
       catch(exception _ex)
       {
        flag = false;
        }
        return flag;
      }
     private vector getgraphfiles(string as[])//获得图片文件
      {
        vector vector = new vector();
        if(as == null)//如果as为空值,则返回vector中的值
         return vector;
         for(int i = 0; i < as.length; i++)//as.length为as[]数组长度
         {
          string s = as[i].touppercase();//设置图片文件文件名的每个字符为大写
          if(isgraphfile(s))//如果为图片格式
           vector.addelement(as[i]);//加入向量中
          }
          return vector;
        }
    private boolean isgraphfile(string stringfilename)
      file://判断文件是否为图形格式
      {
       int i = stringfilename.indexof(".");//
       if(i <= 0 || i == stringfilename.length() - 1)
        return false;
        file://判断文件是否以gif、jpg、jpeg或 png结尾
       string stringextendfilename1 = stringfilename.substring(i + 1);
       return stringextendfilename1.equals("gif") || stringextendfilename1.equals("jpg") || stringextendfilename1.equals("jpeg") || stringextendfilename1.equals("png");
      }
     private void errormessage(string s, httpservletresponse httpservletresponse)
      throws ioexception
      {
       httpservletresponse.setcontenttype("text/html");
       printwriter out = httpservletresponse.getwriter();
       out.println("");
       out.println("");
       out.println("");
       out.println("");
       out.println("");
       out.println("
" + s + "  ");
       out.println("");
       out.println("");
       out.flush();
       out.close();
      }
    private string getfromquery(string strquery, string strquery1)
     {
      if(strquery == null)
       return "";
       int i;
       if((i = strquery.indexof(strquery1)) < 0)
        return "";
        string strquery2 = strquery.substring(i + strquery1.length());
       if((i = strquery2.indexof("&")) < 0)
         return strquery2;
       else
         return strquery2.substring(0, i);
       }
     public string getservletinfo()
      {
       return "旗帜广告系统 ,wayne zheng";
      }
    private static final string cpr = "©wayne zheng";
    private static final string default_site = "www.yesky.com";
    private static final string banner_session = "旗帜广告系统 ,wayne zheng";
    private static final string dir = "dir";
    private static final string log = "log";
    private static final string bannerindex = "bi";
    private static final string edited = "edited";
    private static final string view_postfix = "v";
    private static final string click_postfix = "c";
    private static final string config = "config";
    private static final string mode = "mode";
 
    private static final string id = "id";
    private static final int buffer_size = 4096;
    static string separator = "/";
    private static hashtable cfgs;
    private static hashtable logs;
   }

,欢迎访问网页设计爱好者web开发。