原文档链接:
http://soft.yesky.com/352/2243352.shtml
所用软件或包的版本:
Struts 1.2
Spring 1.2.8
Hibernate 3.1
Oracle 9i
MyEclipse4.1.1
具体代码如下:
TFile类:
package sshfile.model;
import java.sql.Blob;
/**
* TFile generated by MyEclipse - Hibernate Tools
*/
public class TFile implements java.io.Serializable {
// Fields
private String fileId;
private String fileName;
private byte[] fileContent;
private String remark;
// Constructors
/** default constructor */
public TFile() {}
/** full constructor */
public TFile(String fileName, byte[] fileContent, String remark) {
this.fileName = fileName;
this.fileContent = fileContent;
this.remark = remark;
}
// Property accessors
public String getFileId() {
return this.fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getFileName() {
return this.fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public byte[] getFileContent() {
return this.fileContent;
}
public void setFileContent(byte[] fileContent) {
this.fileContent = fileContent;
}
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
TFile.hbm.xml代码:
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
TFileDAO接口代码:
package sshfile.dao;
import java.util.List;
import sshfile.model.TFile;
/**
* DAO 接口
* @author tony.lee
*
*/
public interface TFileDAO {
public void save(TFile tfile);
public void delete(TFile tfile);
public TFile findByFildId(String fileId);
public List findAll();
public int getFilesCount();
public int getCountByQuery();
}
TFileDAO接口实现类代码:
package sshfile.dao;
import sshfile.model.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.util.List;
/**
* DAO 实现类
*
* @author tony.lee
*
*/
public class TfileDAOHibernate extends HibernateDaoSupport implements TFileDAO {
private static final Log log = LogFactory.getLog(TfileDAOHibernate.class);
public void save(TFile tfile) {
log.debug("saving TFile instance:");
try {
getHibernateTemplate().saveOrUpdate(tfile);
// getHibernateTemplate().save(tfile);
getHibernateTemplate().flush();
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(TFile tfile) {
log.debug("deleting TFile instance:");
try {
getHibernateTemplate().delete(tfile);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public TFile findByFildId(String fileId) {
log.debug("getting TFile instance with id: " + fileId);
try {
return (TFile) getHibernateTemplate().get(TFile.class, fileId);
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findAll() {
log.debug("finding all file:");
try {
// return (List)getHibernateTemplate().loadAll(TFile.class);
return (List) getHibernateTemplate().find("from TFile");
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
/**
* 取记录总数(1)
* @return int
*/
public int getFilesCount() {
log.debug("getting file count:");
int count = 0;
//注意:此TFile为对象不是表。
String queryString = "select count(*) from TFile";
try {
count = ((Integer) getHibernateTemplate().iterate(queryString).next()).intValue();
return count;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
//取记录总数(2)
public int getCountByQuery() {
Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException {
String queryString = "select count(*) from TFile";
Query query = session.createQuery(queryString);
return ((Integer)query.iterate().next()).intValue();
}
}, true);
return count.intValue();
}
}
FileService接口代码:
package sshfile.service;
import java.io.OutputStream;
import java.util.List;
import sshfile.web.form.FileActionForm;
/**
* Service 接口
* @author tony.lee
*
*/
public interface FileService {
// 将提交的上传文件保存到数据表中
void save(FileActionForm fileForm);
// 得到T_FILE所示记录
List getAllFile();
// 将某个文件的文件数据写出到输出流中
void write(OutputStream os,String fileId);
// 获取文件名
String getFileName(String fileId);
// 用于删除文件
public void delete(String fileId);
public int getFilesCount();
}
FileService接口实现类代码:
package sshfile.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import sshfile.dao.TFileDAO;
import sshfile.model.TFile;
import sshfile.web.form.FileActionForm;
/**
* Service 实现类
* @author tony.lee
*
*/
public class FileServiceImpl implements FileService {
private TFileDAO fileDAO;
public FileServiceImpl() {
}
//用于将上传的文件信息保存到数据库
public void save(FileActionForm fileForm) {
//将FileActionForm对象中的数据倒入到Tfile对象中
TFile tFile = new TFile();
try {
tFile.setFileContent(fileForm.getFileContent().getFileData());
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
tFile.setFileName(fileForm.getFileContent().getFileName());
tFile.setRemark(fileForm.getRemark());
//调用TfileDAO保存数据。
fileDAO.save(tFile);
}
//用于下载指定文件
public void write(OutputStream os, String fileId) {
TFile tfile = fileDAO.findByFildId(fileId);
try {
os.write(tfile.getFileContent());
os.flush();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//用于删除指定文件
public void delete(String fileId) {
TFile tfile = fileDAO.findByFildId(fileId);
try {
fileDAO.delete(tfile);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
// 得到指定文件的名称(包括扩展名)
public String getFileName(String fileId) {
TFile tfile = fileDAO.findByFildId(fileId);
return tfile.getFileName();
}
// 得到所有文件列表
public List getAllFile() {
return fileDAO.findAll();
}
//得到所有文件数量
public int getFilesCount(){
//return fileDAO.getFilesCount();
return fileDAO.getCountByQuery();
}
//----------------------------------------------------------------------------
public TFileDAO getFileDAO() {
return fileDAO;
}
// 依赖注入fileDAO BEAN
public void setFileDAO(TFileDAO fileDAO) {
this.fileDAO = fileDAO;
}
}
FileAction类代码:
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/JavaClass.xsl
package sshfile.web.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.ModuleException;
import sshfile.service.FileService;
import sshfile.web.form.FileActionForm;
/**
* MyEclipse Struts Creation date: 01-17-2007
*
* XDoclet definition:
*
* @struts.action path="/fileAction" name="fileActionForm" parameter="method" scope="request" validate="true"
* @struts.action-forward name="forward" path="/fileAction.do?method=listAllFile"
* @struts.action-forward name="fileList" path="/file-list.jsp"
*/
public class FileAction extends DispatchAction {
// --------------------------------------------------------- Instance Variables
private FileService fileService;
// --------------------------------------------------------- Methods
// 将上传文件保存到数据库中
public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
FileActionForm fileForm = (FileActionForm) form;
fileService.save(fileForm);
return mapping.findForward("forward");
}
// 列出所有文件
public ActionForward listAllFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws ModuleException {
//int count = fileService.getFilesCount();
//System.out.println(count);
List fileList = fileService.getAllFile();
request.setAttribute("fileList", fileList);
return mapping.findForward("fileList");
}
// 下载指定文件
public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws ModuleException {
FileActionForm fileForm = (FileActionForm) form;
String fileName = fileService.getFileName(fileForm.getFileId());
try {
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;" + "filename="
+ new String(fileName.getBytes(), "UTF-8"));
fileService.write(response.getOutputStream(), fileForm.getFileId());
} catch (Exception e) {
throw new ModuleException(e.getMessage());
}
return null;
}
// 删除指定文件
public ActionForward deleteFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws ModuleException {
FileActionForm fileForm = (FileActionForm) form;
fileService.delete(fileForm.getFileId());
List fileList = fileService.getAllFile();
request.setAttribute("fileList", fileList);
return mapping.findForward("fileList");
}
//----------------------------------------------------------------------------------
public FileService getFileService() {
return fileService;
}
//依赖注入fileService BEAN
public void setFileService(FileService fileService) {
this.fileService = fileService;
}
}
FileActionForm类代码:
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/JavaClass.xsl
package sshfile.web.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
/**
* MyEclipse Struts
* Creation date: 01-17-2007
*
* XDoclet definition:
* @struts.form name="fileActionForm"
*/
public class FileActionForm extends ActionForm {
// --------------------------------------------------------- Instance Variables
/** remark property */
private String remark;
/** fileContent property */
private FormFile fileContent;
/** fileId property */
private String fileId;
// --------------------------------------------------------- Methods
/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
/**
* Returns the remark.
* @return String
*/
public String getRemark() {
return remark;
}
/**
* Set the remark.
* @param remark The remark to set
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* Returns the fileContent.
* @return String
*/
public FormFile getFileContent() {
return fileContent;
}
/**
* Set the fileContent.
* @param fileContent The fileContent to set
*/
public void setFileContent(FormFile fileContent) {
this.fileContent = fileContent;
}
/**
* Returns the fileId.
* @return String
*/
public String getFileId() {
return fileId;
}
/**
* Set the fileId.
* @param fileId The fileId to set
*/
public void setFileId(String fileId) {
this.fileId = fileId;
}
}
file-upload.jsp代码:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
file-update
请选择上传的文件: | |
文件注释: | |
file-list.jsp代码:
<%@page contentType="text/html; charset=UTF-8"%>
<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
返回到上传页面
//////下面是配置文件:
init.properties代码:
datasource.driverClassName=oracle.jdbc.driver.OracleDriver
datasource.url=jdbc:oracle:thin:@localhost:1521:oracle92
datasource.username=scott
datasource.password=tiger
datasource.maxActive=50
datasource.maxIdle=2
datasource.maxWait=120000
datasource.defaultAutoCommit=true
datasource.whenExhaustedAction=1
datasource.validationQuery=select 1 from dual
datasource.testOnBorrow=true
datasource.testOnReturn=false
hibernate.dialect=org.hibernate.dialect.Oracle9Dialect
hibernate.cglib.use_reflection_optimizer=true
hibernate.jdbc.batch_size=25
hibernate.jdbc.fetch_size=50
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
log4j.properties代码:
log4j.rootCategory=INFO, stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=${webapp.root}/WEB-INF/logs/SSHFile.log
log4j.appender.AAA.DatePattern=.yyyy-MM-dd
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n
web.xml代码:
struts-config.xml代码:
parameter="method"
path="/fileAction"
scope="request"
type="org.springframework.web.struts.DelegatingActionProxy">
applicationContext.xml代码:
actionContext.xml代码:
但是发现了一个问题:就是当上传了很多文档后,再上传文档还是可以的,但是从数据库读出来显示到页面上时会出现“内存溢出”的错误。有谁碰到过这个问题吗?若有,请问有什么好的高效的解决方案吗?
以上是所有代码的实现,若有什么不当之处请不吝赐教。。。