自動更新的JSP下載頁面
方法就是通過1個javabean,在每次有訪問到JSP頁面的時候javabean被激發搜尋資料夾的內容,當檔案夾有了更新時,javabean搜尋出更新後的檔案和原來已經存在的檔案一齊列出來供訪問者下載。每個供下載的檔案(比如file.zip)都有一個對應的描述檔案(比如file.txt),這個javabean會把描述檔案.txt的內容作為下載檔案的描述一齊顯示出來作為下載連結的附加資訊,如果沒有提供對應的.txt描述檔案,則會顯示"no descrition"
下面是javabean的內容
/*
* Created on 2004-7-22
* @author lingch
*
* functions:
* 1. search the directory for files.
* 2. return the coresponding .txt description content.
*/
package p;
import java.io.*;
import java.util.*;
public class files_lookup {
File files;
Vector result;
public files_lookup()
{
}
public Vector lookup_files(String path)//---------path should be the downloads dir
{
Vector result=new Vector();
files=new File(path);
String sub_files[];
if(files.isDirectory())
{
sub_files=files.list();//---------list all files under downloads dir
}
else
{
result.add("path "+path+ " is not a dir");
return result;
}
for(int i=0;i<sub_files.length;i++)
{
if(sub_files[i].lastIndexOf(".txt")>=0)
{
continue;//------------- .txt are description files.not for downloading.
}
result.add(sub_files[i]);
}
return result;
}
public String get_file_description(String file_name)//----path should be a file name that collecting info
{
File file=new File(file_name);
String description="no description";
String f_name=file_name.substring( 0,file_name.lastIndexOf("."));
f_name=f_name+".txt";// ------change the extension file name to .txt
FileReader rd;
BufferedReader brd;
try{// read .txt content
rd=new FileReader(f_name);
brd=new BufferedReader(rd);
description=brd.readLine();
String temp;
while((temp=brd.readLine())!=null)
{
description+=temp;
}
brd.close();
}
catch(FileNotFoundException ee)
{
}
catch(IOException ee)
{
}
return description;
}
}
而jsp頁面可以像下面這樣組織
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*" errorPage="" %>
<%@ page language="java" import="p.*" %>
<jsp:useBean id="lb" scope="page" class="p.files_lookup" />
<html>
<head>
<title>lingch's download page</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%
String path=getServletConfig().getServletContext().getRealPath("// ")+" //downloads ";
Vector v=lb.lookup_files(path);
if(v!=null)
{
for(int i=0;i<v.size();i++)
{
%>
<p>file : <a href="downloads/<%out.print(v.get(i));%>"><%out.print(v.get(i));%></a></p>
<p>decription : <%out.print(lb.get_file_description( path+" //"+v.get(i)));%></p >
<hr width="300">
<%
}//for
}//if
%>
<strong> </strong>
</body>
</html>
整個應用的檔案結構如下
downloads/web-inf/web.xml
downloads/web-inf/classes/p/files_lookup.class
downloads/downloads.jsp
downloads/downloads
使用時只需要把要供人下載的檔案放入downloads/downloads就可以了。
啟動tomcat,鍵 入 http://127.0.0.1/downloads/downloads.jsp 可以訪問。