浏览 13052 次
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2007-01-22
原文档链接: 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代码: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse - Hibernate Tools --> <hibernate-mapping> <class name="sshfile.model.TFile" table="T_FILE" > <id name="fileId" type="string"> <column name="FILE_ID" length="32" /> <generator class="uuid.hex"></generator> </id> <property name="fileName" type="string"> <column name="FILE_NAME" length="100" /> </property> <property name="fileContent" type="org.springframework.orm.hibernate3.support.BlobByteArrayType" lazy="true"> <column name="FILE_CONTENT" /> </property> <property name="remark" type="string"> <column name="REMARK" length="400" /> </property> </class> </hibernate-mapping> 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" %> <html> <head> <title> file-update </title> </head> <body bgcolor="#ffffff"> <html:form action="/fileAction.do?method=upload" method="post" enctype="multipart/form-data"> <table width="100%" border="0"> <tr> <td align="right">请选择上传的文件:</td> <td><html:file property="fileContent"/></td> </tr> <tr> <td align="right">文件注释:</td> <td><html:textarea cols="30" property="remark"/></td> </tr> <tr> <td colspan="2" align="center"><html:submit value="提交"/></td> </tr> </table> </html:form> </body> </html> 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"%> <html> <head> <title>file-download</title> </head> <body bgcolor="#ffffff"> <ol> <logic:iterate id="item" name="fileList" scope="request"> <li> <a href='fileAction.do?method=download&fileId=<bean:write name="item" property="fileId"/>'> <bean:write name="item" property="fileName"/></a> <a href='fileAction.do?method=deleteFile&fileId=<bean:write name="item" property="fileId"/>'> delete</a> </li> </logic:iterate> </ol> <a href='file-upload.jsp'>返回到上传页面</a> </body> </html> //////下面是配置文件: 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代码: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!--默认读取applicationContext.xml,也可以读取多个自定义的配置文件,用逗号隔开 --> <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/actionContext.xml</param-value> </context-param> --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> --> <!--使用struts控制view层 --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> struts-config.xml代码: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans > <form-bean name="fileActionForm" type="sshfile.web.form.FileActionForm" /> </form-beans> <global-exceptions /> <global-forwards /> <action-mappings > <action attribute="fileActionForm" name="fileActionForm" parameter="method" path="/fileAction" scope="request" type="org.springframework.web.struts.DelegatingActionProxy"> <forward name="forward" path="/fileAction.do?method=listAllFile" /> <forward name="fileList" path="/file-list.jsp" /> </action> </action-mappings> <message-resources parameter="sshfile.web.ApplicationResources" /> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml,/WEB-INF/actionContext.xml" /> </plug-in> </struts-config> applicationContext.xml代码: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- 初始化文件导入配置 //--> <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>/WEB-INF/init.properties</value> </property> </bean> <!-- dataSource配置 //--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"> <value>${datasource.driverClassName}</value> </property> <property name="url"> <value>${datasource.url}</value> </property> <property name="username"> <value>${datasource.username}</value> </property> <property name="password"> <value>${datasource.password}</value> </property> <property name="maxActive"> <value>${datasource.maxActive}</value> </property> <property name="maxIdle"> <value>${datasource.maxIdle}</value> </property> <property name="maxWait"> <value>${datasource.maxWait}</value> </property> <property name="defaultAutoCommit"> <value>${datasource.defaultAutoCommit}</value> </property> </bean> <!-- Lob字段的处理句柄配置 //--> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" lazy-init="true" /> <bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler" lazy-init="true"> <property name="nativeJdbcExtractor"> <ref local="nativeJdbcExtractor" /> </property> </bean> <!-- sessionFactory配置 //--> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- 为处理Blob类型字段的句柄声明 //--> <property name="lobHandler" ref="lobHandler" /> <!-- hibernate一些额外配置 //--> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.cglib.use_reflection_optimizer">${hibernate.cglib.use_reflection_optimizer}</prop> <prop key="show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop> <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop> </props> </property> <!-- hibernate映射配置 //--> <property name="mappingResources"> <list> <value>sshfile/model/TFile.hbm.xml</value> </list> </property> <!-- 也可以这么用 <property name="mappingDirectoryLocations"> <list> <value>classpath:/sshfile/model</value> </list> </property> //--> </bean> <!--定义事务bean--> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory" /> </property> </bean> <!--定义事务拦截器bean --> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <!--事务拦截器bean需要依赖注入一个事务管理器--> <property name="transactionManager" ref="transactionManager" /> <property name="transactionAttributes"> <!--下面定义事务传播属性--> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="save">PROPAGATION_REQUIRED</prop> <prop key="write">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> <!-- 定义BeanNameAutoProxyCreator--> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <!-- 指定对满足哪些bean name的bean自动生成业务代理 --> <property name="beanNames"> <!-- 下面是所有需要自动创建事务代理的bean--> <list> <value>fileService</value> <!--此处可增加其他需要自动创建事务代理的bean--> </list> </property> <!--下面定义BeanNameAutoProxyCreator所需的事务拦截器--> <property name="interceptorNames"> <list> <value>transactionInterceptor</value> <!-- 此处可增加其他新的Interceptor --> </list> </property> </bean> <!-- DAO bean//--> <bean id="fileDAO" class="sshfile.dao.TfileDAOHibernate"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- service bean//--> <bean id="fileService" class="sshfile.service.FileServiceImpl"> <property name="fileDAO"> <ref bean="fileDAO" /> </property> </bean> </beans> actionContext.xml代码: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean name="/fileAction" class="sshfile.web.action.FileAction" singleton="false"> <property name="fileService"> <ref bean="fileService" /> </property> </bean> </beans> 但是发现了一个问题:就是当上传了很多文档后,再上传文档还是可以的,但是从数据库读出来显示到页面上时会出现“内存溢出”的错误。有谁碰到过这个问题吗?若有,请问有什么好的高效的解决方案吗? 以上是所有代码的实现,若有什么不当之处请不吝赐教。。。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2007-01-25
楼主,是不是applicationContext.xml的内容和struts-config.xml的内容贴反了呀??怎么感觉怪怪的?
|
|
返回顶楼 | |
发表时间:2007-01-25
试一试
|
|
返回顶楼 | |
发表时间:2007-01-31
谢谢city_moon的提醒,我已经对内容做了相应修改。
|
|
返回顶楼 | |
发表时间:2007-05-08
如果要用mysql或者access数据库也改那些配置了?
|
|
返回顶楼 | |
发表时间:2007-05-08
应该是与数据库无关的吧,可是我用mysql不行.
|
|
返回顶楼 | |
发表时间:2007-05-13
如果用mysql的话,修改init.properties文件如下部分即可:
datasource.driverClassName=com.mysql.jdbc.Driver datasource.url=jdbc:mysql://IP:port/testdb hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect |
|
返回顶楼 | |
发表时间:2007-05-13
testdb为数据库名
|
|
返回顶楼 | |