对于一个商务网站来说广告系统是必不可少的一个好的广告系统是一个网站稳定收入的基础而旗帜广告(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;//以时间戳和c或v为文件名来写日志文件
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;
}