现在的位置: 首页 > 综合 > 正文

自动更新的JSP下载页面

2013年10月11日 ⁄ 综合 ⁄ 共 2449字 ⁄ 字号 评论关闭

自动更新的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 可以访问。

抱歉!评论已关闭.