熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

用Java Servlet構建旗幟廣告系統

2022-06-13   來源: Java核心技術 

  對於一個商務網站來說廣告系統是必不可少的一個好的廣告系統是一個網站穩定收入的基礎而旗幟廣告(banner)則是網站廣告中占絕大部分的廣告因此開發一個旗幟廣告系統就非常重要了利用Java Servlet 我們可以很輕松的構建屬於我們自己的旗幟廣告系統 

  我們一般在網頁上放上一些圖片設置它們的鏈接指向廣告客戶的網頁然後產生日志文件存放浏覽的人數浏覽者的IP等信息這就是開發旗幟廣告系統的一般思路 

  下面我想結合一個例程來介紹一下如何使用Java Servlet來構建旗幟廣告系統下面這個例子中你必須在你的HTML文件中使用<IMG> 標簽 

  用法有三種是 

  ) Banner?config_file 或Banner?config=config_file 

  例如 

   <IMG height= src=http://localhost/servlet/Banner?config_file width=> 

  用這種方法你就可以顯示不同的圖片了 

  ) 你也可以為每一幅圖片設置自己的重定向URL只需在你的設置中添加文件描述見下面的例子Servlet也需要更多的描述參數     

   <IMG height= src=http://localhost/servlet/Banner?config=config_file&mode= width=> 

這樣你就可以支持標准的旗幟廣告了 

  )你也可以在同一個頁面上有多個旗幟廣告你只需要在參數中加入id=某個整數值就可以了這個值必須是一個你的頁面內唯一的整數值!例如對於第一個banner的描述為     

   <IMG height= src=http://localhost/servlet/Banner?config=config_file&mode=&id= width=> 

  第二個為 

   <IMG height= src=http://localhost/servlet/Banner?config=config_file&mode=&id= width=> 

  有的朋友會問了config_file是什麼文件呀? 它是一個文本文件用來描述Servlet的設置信息你能在你的主機的任何地方保存這個文件現把參數介紹一下這個配置文件有三個參數分別為 

  dir=some_directory

  解釋 dir是你的旗幟廣告文件存放的目錄可以使用的圖片格式有JPG GIFPNG JPEG等這個參數是必須有的否則系統會報錯

  bannerfilename=some_url 

  解釋 banner文件使用下面的格式例如 

   bannergif=http://wwwyeskycom/ 

   bannerjpg=http://wwwyeskycom/ 

  log=some_directory_to_store_log_file

  解釋存放日志文件的目錄可以是服務器上的任何目錄

  附錄日志文件(log file)及格式 

  Banner 系統每天會自動產生兩個日志文件分別為ddmmyyyyvtxt和ddmmyyyyctxt 第一個文件保存浏覽banner的記錄第二個文件保存重定向的記錄兩個文件都是文本文件每一行包括一條記錄紀錄格式是 

  IP地址 日期 圖片文件 用戶代理 重定向記錄 (只用於 *ctxt文件) 字段之間用空格隔開 


  附錄Bannerjava源程序 

  import javaio*; 

  import javautil*; 

  import javaxservlet*; 

  import javaxservlethttp*; 

  public class Banner extends HttpServlet 

   { 
    public Banner(){ } 

    //讀取配置文件內容 

    private boolean readConfig(String sConfig Hashtable hashtable) 

    { 
     try 
      { 

        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream(sConfig)));// 設置緩沖區讀入一個配置文件 

       String sLineInformation;// 

       while((sLineInformation = bufferedreaderreadLine()) != null) 

       { 
        sLineInformation = sLineInformationtrim();//去除字符串中的空格 

        if(sLineInformationlength() > )//如果字符串sLineInformation的長度大於零 { 

         int i = sLineInformationindexOf(=); 

      if(i > && i < sLineInformationlength() && sLineInformationcharAt() != # && !sLineInformationstartsWith(//))
       //配置文件的每一行參數必須以不為#或//開頭的字符串

          hashtableput(sLineInformationsubstring( i)trim()toLowerCase() sLineInformationsubstring(i + )trim());

          }

         }

        bufferedreaderclose();

        File file = new File(sConfig);//創建一個配置文件

        hashtableput(edited StringvalueOf(filelastModified()));

        }

       catch(Exception _ex)

       {
        return false;

       }

      String sDirInfo = (String)hashtableget(dir);//取得目錄參數

      if(sDirInfo != null)//如果目錄參數是空值

       {
        if(!sDirInfoendsWith(separator))//如果sDirInfo不是以分隔符結尾那麼

        {

         sDirInfo = sDirInfo + separator;//給sDirInfo加上分隔符

         hashtableremove(dir);//移去哈希表變量中的dir

         hashtableput(dir sDirInfo);
        }

      File file = new File(sDirInfo);

      String as[] = filelist();

      if(as == null) {

       hashtableremove(dir);
       }

      sDirInfo = (String)hashtableget(log);

      if(sDirInfo != null)

       {
        if(!sDirInfoendsWith(separator))

         {
          sDirInfo = sDirInfo + separator;

          hashtableremove(log);

          hashtableput(log sDirInfo);

         }

      File file = new File(sDirInfo);

      String as[] = filelist();

      if(as == null) {

       hashtableremove(log);

       }
      return true;

     }

    private Hashtable getConfig(String s)//取得配置

     {
      Hashtable hashtable = (Hashtable)cfgsget(s);

      if(hashtable != null)//如果配置不為空

      try

       {
        String s = (String)hashtableget(edited);

        File file = new File(s);

        if(!sequals(StringvalueOf(filelastModified()))){

        //如果s的值不等於文件最後一次修改的值則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

         {
          cfgsput(s hashtable);

          return hashtable;

         }

        }
     public void init(ServletConfig servletconfig)//初始化配置參數

      throws ServletException {

        //如果出錯拋出一個ServletException錯誤

         superinit(servletconfig);

         separator = SystemgetProperty(fileseparator);//取得分隔符

         cfgs = new Hashtable();//設置配置變量

         logs = new Hashtable();//設置日志變量

         Systemoutprintln(? Wayne Zheng );//屏幕輸出我的郵箱地址

        }
     public void destroy()  {  }

     public void doPost(HttpServletRequest request HttpServletResponse response)             //發送POST請求

      throws ServletException IOException

       { doGet(request response); }

      public void doGet(HttpServletRequest httpservletrequest HttpServletResponse httpservletresponse) //讀取GET

      throws ServletException IOException

      {
       String strConfig = httpservletrequestgetQueryString();

       //讀取請求字符串

       if(strConfig == null)//如果字符串為空

        strConfig = ;//那麼設置strConfig為空

        if(strConfiglength() == )

        //如果strConfig長度為零那麼顯示錯誤信息

        {
         errorMessage(無配置信息! httpservletresponse);

         return;

        }

        String strConfig = getFromQuery(s config=);//同上

        if(strConfiglength() == ){

         strConfig = strConfig;

         Hashtable hashtable = getConfig(strConfig);

         if(hashtable == null)

         {
           errorMessage(配置信息錯誤! httpservletresponse);

           return;

         }

         if(hashtableget(dir) == null)

         //如果哈希表中dir為空值則輸出錯誤信息

         {
          errorMessage(不能打開數據目錄 httpservletresponse);

          return;

         }

       String strConfigMode = getFromQuery(strConfig mode=);//讀取配置中的mode值

       if(strConfigModelength() == ){//如果沒有mode值

        strConfigMode = ;//則設mode值為

        String strConfigId = getFromQuery(strConfig id=);//讀取配置中的id值

        if(strConfigIdlength() == ){ file://如果沒有id值

          strConfigId = ;//則設id值為

          HttpSession httpsession = httpservletrequestgetSession(true);

          if(strConfigModeequals())

          file://如果strConfigMode的值為則顯示banner廣告

          {

           showBanner(hashtable strConfigId httpsession httpservletrequest httpservletresponse);

           return;

           }


else //否則轉向banner所指的站點 

           { 

            goToSite(hashtable strConfigId httpsession httpservletrequest httpservletresponse); 

            return; 

           } 

         } 

       private void goToSite(Hashtable hashtable String s HttpSession httpsession HttpServletRequest httpservletrequest HttpServletResponse httpservletresponse)//轉向站點 

        throws IOException //如果有任何錯誤拋出IOException錯誤 

        { 

         String sitename;//定義站點名 

         if(httpsession == null)//如果httpsession為空 

          { 

           sitename = getFirstSite(hashtable);//站點名為哈希表中的第一個站點名 

           } 

         else //否則 

          { 
           Hashtable hashtable = (Hashtable)httpsessiongetValue(旗幟廣告系統 Wayne Zheng); 

         if(hashtable == null){ //如果哈希表hashtable為空值則 

           sitename = getFirstSite(hashtable);// 站點名為哈希表(hashtable)中的第一個站點名 

         else 

           sitename = (String)hashtableget(s); 

         } 

        if(sitename == null) 

        //如果站點名為空值則站點名為默認值http://wwwyeskycom 

        sitename = http://wwwyeskycom

        String s

        if(hashtableget(log) != null && (s = getFileByUrl(hashtable s)) != null){ 

         writeLog(hashtable s sitename c httpservletrequest); 

         httpservletresponsesendRedirect(sitename); 

         } 

    private void showBanner(Hashtable hashtable String s HttpSession httpsession HttpServletRequest httpservletrequest HttpServletResponse httpservletresponse) 

    throws IOException 

    { 
     String s = (String)hashtableget(dir); 

     File file = new File(s); 

     Vector vector; 

     if(file == null) 

      { 

       vector = new Vector(); 

      } 

     else 

      { 

       String as[] = filelist(); 

       vector = getGraphFiles(as); 

      } 

     if(vectorsize() ==

      { 
       httpservletresponsesetContentType(text/html); 

       PrintWriter out = httpservletresponsegetWriter(); 

       outprintln(目錄是空的!); 

       outflush(); 
 
       outclose(); 

       return; 

      } 

     int i; 

     if(httpsession != null) 

      synchronized(hashtableget(dir)) 

      { 

       Integer integer; 

       int j; 

       if((integer = (Integer)httpsessiongetValue(bi)) == null){ 

        j =

       else 

        j = integerintValue(); 

        if(j >= vectorsize()) {

         j =

         i = j; 

         if(++j >= ){ 

          j =

          httpsessionputValue(bi new Integer(j)); 

         } 

         else 

           i =

           String s = (String)vectorelementAt(i); 

           String s

           if(httpsession != null && (s = getUrl(hashtable s)) != null) 

            { 

             Hashtable hashtable

             if((hashtable = (Hashtable)httpsessiongetValue(旗幟廣告系統 Wayne Zheng)) == null){ 

              hashtable = new Hashtable(); 

              hashtableput(s s); 

              httpsessionputValue(旗幟廣告系統 Wayne Zheng hashtable); 

              } 

             if(hashtableget(log) != null) {

              writeLog(hashtable s v httpservletrequest); 

              outputBanner(s hashtable httpservletresponse); 

              vector = null; 

              } 

    private void writeLog(Hashtable logHashtable String logString String logString String logString HttpServletRequest httpservletrequest)//寫日志的函數 

    { 

     String logString = (String)hashtableget(log); 

     String logString = getLogString(logString httpservletrequest) + \ + logString + \

     GregorianCalendar gregoriancalendar = new GregorianCalendar(); 

     //獲取當前的時間 

     gregoriancalendarsetTime(new Date()); 

    String logString = logString + stringDate(gregoriancalendar) + logString + txt;//以時間戳和cv為文件名來寫日志文件 

     saveLog(hashtable logString logString); 

     } 

  private void writeLog(Hashtable logHashtable String logString String logString HttpServletRequest httpservletrequest) file://寫日志文件 

     { 

      String logString = (String)logHashtableget(log); 

      String logString = getLogString(logString httpservletrequest); 

      GregorianCalendar gregoriancalendar = new GregorianCalendar(); 

      gregoriancalendarsetTime(new Date()); 

      String logString = logString + stringDate(gregoriancalendar) + logString + txt

      saveLog(logHashtable logString logString); 

     } 

    private void saveLog(Hashtable hashtable String s String s)//把日志文件保存在硬盤上 

     { 

       synchronized(hashtableget(log)) 

      { 

       try 

        { 

         FileWriter filewriter = new FileWriter(s true); 

         PrintWriter printwriter = new PrintWriter(filewriter); 

         printwriterprintln(s); 

         printwriterflush(); 

         printwriterclose(); 

         filewriterclose(); 

        } 

       catch(Exception _ex) { } 

     } 

    } 

   private String getLogString(String s HttpServletRequest httpservletrequest)     //取得日志字符串 
    { 

     String s = httpservletrequestgetRemoteAddr(); 

     //取得遠程的訪問者的IP地址 

     String s = httpservletrequestgetHeader(UserAgent); 

     String s = httpservletrequestgetHeader(Referer); 

     String s = \ + s + \

     if(s == null) 

      s =

      if(s == null) 

       s =

      else 

       s = \ + s + \

      if(s == null) 

       s =

      else 

       s = \ + s + \

      return s + [ + new Date() + ] + s + + s + + s

     } 
   private String stringDate(Calendar calendar) //取得時間戳 

    { 

      String s = StringvalueOf(calendarget()); 

      String s = StringvalueOf(calendarget()); 

      if(slength() ==

        s = + s

        s = s + s

        s = StringvalueOf(calendarget()); 

        if(slength() ==

         s = + s

         return s + s

       } 

    private String getFileByUrl(Hashtable hashtable String s) 

     { 

      for(Enumeration enumeration = hashtablekeys(); enumerationhasMoreElements();) 

       //hashtable的keys()方法返回了哈希表關鍵字的枚舉enumeration的hasMoreElements()方法測試枚舉重是否還有其他元素 

       { 

        String s = (String)enumerationnextElement();

         //讓s的值為enumeration的下一個元素值 

        if(sequals(hashtableget(s)))//如果s的值為s的值則 

         return s;//返回s的值 

       } 

       return null; 

      } 

    private String getFirstSite(Hashtable hashtable)//取得第一個站點的名字 

     { 

      String s = (String)hashtableget(dir); 

      File file = new File(s); 

      if(file == null) 

        return null; 

        String as[] = filelist(); 

        Vector vector = getGraphFiles(as); 

        //設置Vector向量變量來獲取圖形文件 

        if(vectorsize() == )//如果沒有圖形文件則返回空值 

          return null; 

        else 

          return getUrl(hashtable (String)vectorelementAt()); 

        } 

    private String getUrl(Hashtable hashtable String s)//取得URL 

     { 

       String s = stoLowerCase();//設置s為s的小寫形式 

       for(Enumeration enumeration = hashtablekeys(); enumerationhasMoreElements();) 

       { 

        String s = (String)enumerationnextElement(); 

        if(sequals(stoLowerCase())) 

         return (String)hashtableget(s); 

       } 

      return null; 
    } 

   private void outputBanner(String s Hashtable hashtable HttpServletResponse httpservletresponse)//輸出banner廣告 

    throws IOException//如果有錯則拋出IOException錯誤 

    { 

     String s = (String)hashtableget(dir) + s; 

     httpservletresponsesetHeader(Cachecontrol nostore); 

     httpservletresponsesetHeader(Pragma nocache); 

     httpservletresponsesetDateHeader(Expires L); 

     httpservletresponsesetContentType(image/ + ssubstring(sindexOf() + )); 

     javaxservletServletOutputStream servletoutputstream = httpservletresponsegetOutputStream(); 

     dumpFile(s servletoutputstream); 

     servletoutputstreamflush(); 

     servletoutputstreamclose(); 

     } 

    private boolean dumpFile(String s OutputStream outputstream) 

     { 

      byte abyte[] = new byte[]; 

      boolean flag = true; 

      try 

       { 

        FileInputStream fileinputstream = new FileInputStream(s); 

        int i; 

        while((i = fileinputstreamread(abyte)) !=

         outputstreamwrite(abyte i); 

         fileinputstreamclose(); 

         } 

      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 = ; i < aslength; i++)//aslength為as[]數組長度

        {

         String s = as[i]toUpperCase();//設置圖片文件文件名的每個字符為大寫

         if(isGraphFile(s))//如果為圖片格式

          vectoraddElement(as[i]);//加入向量中

         }

         return vector;

       }

   private boolean isGraphFile(String stringFileName)      //判斷文件是否為圖形格式

     {

      int i = stringFileNameindexOf();//

      if(i <= || i == stringFileNamelength() )

       return false;

       //判斷文件是否以GIFJPGJPEG或 PNG結尾

      String stringExtendFileName = stringFileNamesubstring(i + );

      return stringExtendFileNameequals(GIF) || stringExtendFileNameequals(JPG) || stringExtendFileNameequals(JPEG) || stringExtendFileNameequals(PNG);

     }

    private void errorMessage(String s HttpServletResponse httpservletresponse)

     throws IOException

     {
      httpservletresponsesetContentType(text/html);

      PrintWriter out = httpservletresponsegetWriter();

      outprintln();

      outprintln();

      outprintln();

      outprintln();

      outprintln();

      outprintln( + s + );

      outprintln();

      outprintln();

      outflush();

      outclose();

     }
   private String getFromQuery(String strQuery String strQuery)

    {

     if(strQuery == null)

      return ;

      int i;

      if((i = strQueryindexOf(strQuery)) < )

       return ;

       String strQuery = strQuerysubstring(i + strQuerylength());

      if((i = strQueryindexOf()) < )

        return strQuery;

      else

        return strQuerysubstring( i);

      }
    public String getServletInfo()

     {

      return 旗幟廣告系統 Wayne Zheng;

     }

   private static final String CPR = ? Wayne Zheng ;

   private static final String DEFAULT_SITE = wwwyeskycom;

   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 = ;

   static String separator = /;

   private static Hashtable cfgs;

   private static Hashtable logs;

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/27253.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.