ITeye博客

Struts+Spring+Hibernate实现上传下载(MyEclipse版)

tony.lee · 2007-01-22 13:32 · Spring · Myeclipse · Spring · Struts · Hibernate · log4j · Markdown

在天极网看了一篇用JBuilder实现的“Struts+Spring+Hibernate实现上传下载”文章,觉得还不错。今天有空我用MyEclipse工具把它重新实现了一边,并增加了一些功能。 原文档链接: http://soft.yesky.com/352/2243352.shtml 所用软件或包的版本: Struts 1.2 Spring 1.2.8 Hibernate 3.1 Oracle 9i MyEclipse4.1.1 具体代码如下: [b]TFile类:[/b] 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; } } [b]TFile.hbm.xml代码:[/b] [b]TFileDAO接口代码:[/b] 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(); } [b]TFileDAO接口实现类代码:[/b] 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(); } } [b]FileService接口代码:[/b] 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(); } [b]FileService接口实现类代码:[/b] 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; } } [b]FileAction类代码:[/b] //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; } } [b]FileActionForm类代码:[/b] //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; } } [b]file-upload.jsp代码:[/b] <%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> file-update

请选择上传的文件: 文件注释:

[b]file-list.jsp代码:[/b] <%@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"%> file-download

  1.       delete

返回到上传页面 //////下面是配置文件: [b]init.properties代码:[/b] 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 [b]log4j.properties代码:[/b] 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 [b]web.xml代码:[/b] log4jConfigLocation /WEB-INF/log4j.properties log4jRefreshInterval 60000 org.springframework.web.util.Log4jConfigListener org.springframework.web.util.IntrospectorCleanupListener encodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 encodingFilter /* action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml debug 3 detail 3 0 action *.do [b]struts-config.xml代码:[/b] [b]applicationContext.xml代码:[/b] /WEB-INF/init.properties ${datasource.driverClassName} ${datasource.url} ${datasource.username} ${datasource.password} ${datasource.maxActive} ${datasource.maxIdle} ${datasource.maxWait} ${datasource.defaultAutoCommit} ${hibernate.dialect} ${hibernate.cglib.use_reflection_optimizer} ${hibernate.show_sql} ${hibernate.jdbc.fetch_size} ${hibernate.jdbc.batch_size} sshfile/model/TFile.hbm.xml PROPAGATION_REQUIRED,readOnly PROPAGATION_REQUIRED,readOnly PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly fileService transactionInterceptor [b]actionContext.xml代码:[/b] 但是发现了一个问题:就是当上传了很多文档后,再上传文档还是可以的,但是从数据库读出来显示到页面上时会出现“内存溢出”的错误。有谁碰到过这个问题吗?若有,请问有什么好的高效的解决方案吗? 以上是所有代码的实现,若有什么不当之处请不吝赐教。。。

评论(8)

  1. #8 楼 · tony.lee · 2007-05-13 09:48

    testdb为数据库名

  2. #7 楼 · tony.lee · 2007-05-13 09:47

    如果用mysql的话,修改init.properties文件如下部分即可: datasource.driverClassName=com.mysql.jdbc.Driver datasource.url=jdbc:mysql://IP:port/testdb hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect

  3. #6 楼 · fishinlove · 2007-05-08 15:03

    应该是与数据库无关的吧,可是我用mysql不行.

  4. #5 楼 · fishinlove · 2007-05-08 09:12

    如果要用mysql或者access数据库也改那些配置了?

  5. #4 楼 · luckne · 2007-02-02 11:14

    试一试,看看

  6. #3 楼 · tony.lee · 2007-01-31 15:14

    谢谢city_moon的提醒,我已经对内容做了相应修改。

  7. #2 楼 · xuehongliang · 2007-01-25 09:46

    试一试

  8. #1 楼 · city_moon · 2007-01-25 09:25

    楼主,是不是applicationContext.xml的内容和struts-config.xml的内容贴反了呀??怎么感觉怪怪的?

评论功能维护中,当前仅展示历史评论。