`
t641339564
  • 浏览: 27448 次
  • 性别: Icon_minigender_1
  • 来自: 贵阳
社区版块
存档分类
最新评论

struts1.2 + Hibernate3实现文件上传下载与其他操作

    博客分类:
  • java
阅读更多

uploadAction.java(上传文件逻辑的处理,Java代码):
package org.upload;

import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.upload.Uploadfile;
import org.upload.UploadfileDAO;
import org.hibernate.*;
import java.util.*;
public class UploadAction extends Action {

private Uploadfile upfile;
private UploadfileDAO dao;

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws HibernateException, UnsupportedEncodingException {
UploadForm uploadForm = (UploadForm) form;
String msg = ""; //提示信息
//获取以下的操作句柄
Hashtable fileh = uploadForm.getMultipartRequestHandler().getFileElements();
for (Enumeration e = fileh.keys(); e.hasMoreElements();) {  //遍历节点
String key = (String) e.nextElement();
FormFile file = null;
file = (FormFile) fileh.get(key);
String fileName = file.getFileName();
if(fileName.equals("")) //检测文件名是否合法
continue;
try {
InputStream stream = file.getInputStream(); //获取文件输入流
OutputStream bos = new FileOutputStream(getServlet()
.getServletContext().getRealPath("/") + "file/" + fileName);
int bytesRead = 0;
byte[] buffer = new byte[2048]; // 2KB buffer
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
upfile = new Uploadfile(fileName,new Float(file.getFileSize()), new java.util.Date());
//数据持久化
dao = new UploadfileDAO();
dao.save(upfile);
} catch (FileNotFoundException e1) {
msg = "Error occurs when uploading.FileNotFoundexception";
request.setAttribute("error", msg);
return mapping.findForward("fail");
} catch (IOException e2) {
msg = "Error occurs when uploading.IOexception";
request.setAttribute("error", msg);
return mapping.findForward("fail");
} catch (Exception e3) {
msg = "Error occurs when uploading.Unknown exception";
request.setAttribute("error", msg);
return mapping.findForward("fail");
}}
return mapping.findForward("success");
}}

DownloadAction.java (下载文件逻辑的处理,Java代码):
package org.upload;
import java.io.IOException;
import java.io.*;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.*;

public class DownloadAction extends Action {
private UploadfileDAO dao;
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws HibernateException, IOException {
dao = new UploadfileDAO();
Integer id = new Integer(request.getParameter("id"));
String fileName = "";
fileName = dao.getfileName(id);
File file = new File(getServlet().getServletContext().getRealPath("/")
+ "file/" + fileName);
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(os);
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
int bytesRead = 0;
byte[] buffer = new byte[1024 * 2];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);//buffer read
}
bos.flush();bos.close();
is.close();os.close();

return null;
}}

ActionForm层:UploadForm.java:
package org.upload;
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;
public class UploadForm extends ActionForm {
private FormFile file;

@Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}

@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.file = null;
}

public FormFile getFile() {
return file;
}

public void setFile(FormFile file) {
this.file = file;
}}

支持中文处理的过滤器Filter:
package org.upload;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Filefilter implements Filter {

private String charset;
public void destroy() {  }

public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
    req.setCharacterEncoding(charset); //utf-8 recommended
    chain.doFilter(req, res);
}

public void init(FilterConfig config) throws ServletException {
    charset = config.getInitParameter("charset");
}}

po层:pojo:
package org.upload;
import java.util.Date;

public class Uploadfile implements java.io.Serializable {
private Integer id;
private String fileName;
private Float fileSize;
private Date uploadTime;

public Integer getId() {
return this.id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFileName() {
return this.fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public Float getFileSize() {
return this.fileSize;
}

public void setFileSize(Float fileSize) {
this.fileSize = fileSize;
}

public Date getUploadTime() {
return this.uploadTime;
}

public void setUploadTime(Date uploadTime) {
this.uploadTime = uploadTime;
}

public Uploadfile() {
}

public Uploadfile(Integer id) {
this.id = id;
}

public Uploadfile(String fileName, Float fileSize, Date uploadTime) {
this.fileName = fileName;
this.fileSize = fileSize;
this.uploadTime = uploadTime;
}}

相应的hibernate ROM数据库映射文件:.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
">
<hibernate-mapping>
<class name="org.upload.Uploadfile" table="uploadfile">
<id column="id" name="id">
<generator class="native" /></id> <!-- 此处使用了MySQL数据库-->
<property column="fileName" name="fileName" length="50" type="string" />
<property column="fileSize" name="fileSize" type="float" />
<property column="uploadTime" name="uploadTime" type="timestamp" />
</class>
</hibernate-mapping>

dao层代码(UploadfileDAO.java)比较简单,
实现几个方法,比如save(), del(), findAllFile()等,

package org.upload;

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UploadfileDAO {
private Session session = null;
private static SessionFactory factory = new Configuration().configure().buildSessionFactory();

public UploadfileDAO() throws HibernateException {   
    this.session = factory.openSession();
}

public void save(Uploadfile upfile) throws HibernateException {
    Transaction tx = this.session.beginTransaction();
    this.session.save(upfile);
    tx.commit();
    this.session.close();
}

public boolean del(Uploadfile file) throws HibernateException {
Transaction tx = this.session.beginTransaction();
this.session.delete(file);
tx.commit();
this.session.close();
return true;
}

public String getfileName(Integer id) throws HibernateException {
Transaction tx = this.session.beginTransaction();
String filename = "";
String hql = "SELECT uf.fileName from Uploadfile as uf where uf.id=:id";
Query q = this.session.createQuery(hql);
q.setInteger("id", id.intValue());
List list = q.list();
tx.commit();
Iterator it = list.iterator();
filename = (String) it.next();
this.session.close();
return filename;
}

public Uploadfile findById(Integer id) throws HibernateException {
Transaction tx = this.session.beginTransaction();
Uploadfile upfile = null;
String hql = "from Uploadfile as uf where uf.id=:id";
Query q = this.session.createQuery(hql);
q.setInteger("id", id);
List l = q.list();
tx.commit();
Iterator it = l.iterator();
upfile = (Uploadfile) it.next();
this.session.close();
return upfile;
}

public List findAllFile() throws HibernateException {
Transaction tx = this.session.beginTransaction();
List arrayList = null;
String hql = "from Uploadfile as uf";
Query q = this.session.createQuery(hql);
arrayList = q.list();
tx.commit();
this.session.close();
return arrayList;
}}

分享到:
评论

相关推荐

    OA办公自动化管理系统(Struts1.2+Hibernate3.0+Spring2+DWR).rar

    - **文档管理**:文件上传、下载、共享,版本控制。 - **会议管理**:预约、通知、记录。 - **日程安排**:个人及团队的日程规划。 - **公告通知**:发布、订阅公司内部消息。 - **项目管理**:跟踪项目进度,分配...

    struts1.2+spring2.5+hibernate3.2学习实例(Eclipse)

    由于上传限制,lib包不能上传,大家可以下载spring2.5版本的支持库(下最大的那个zip包),全部加进去就行了,还有mysql的连接包,项目很简单,直接导入eclipse,就可以使用,包内有mysql的sql文件,框架已经搭好,...

    struts1.2+Hibernate3.0编写的人事管理系统

    Struts1.2是MVC(Model-View-Controller)架构的一种实现,主要用于处理用户界面与业务逻辑之间的交互,而Hibernate3.0则是一个强大的对象关系映射(ORM)工具,它简化了数据库操作,使得开发者可以使用Java对象来...

    OA办公自动化管理系统(Struts1.2+Hibernate3.0+Spring2+DWR).zip

    本项目使用的技术栈是Struts1.2、Hibernate3.0、Spring2以及Direct Web Remoting (DWR)。下面将详细阐述这些技术在系统中的作用。 1. **Struts1.2**:Struts是一个开源的MVC框架,用于构建Java Web应用程序。在OA...

    远程教育系统(Struts1.2+Hibernate3.1+Spring2.0+Tomcat5.0+SqlServer2005)

    远程教育系统是一个基于Java技术栈的在线学习平台,利用了Struts1.2、Hibernate3.1、Spring2.0和Tomcat5.0等组件,搭配SqlServer2005数据库,构建了一个功能完善的系统。这里我们将深入探讨这些技术及其在远程教育...

    java_jsp项目源码_OA办公自动化管理系统(Struts1.2+Hibernate3.0+Spring2+DWR).rar

    OA办公自动化管理系统是一款基于Struts1.2、Hibernate3.0、Spring2和DWR的综合性企业级应用解决方案,旨在帮助企业实现高效、便捷的办公管理。该系统具备以下功能: 1. 用户管理:支持用户注册、登录、权限分配、...

    spring+struts+hibernate实现文件的上传和下载

    【Spring+Struts+Hibernate 实现文件上传和下载】 在 J2EE 开发中,文件的上传和下载是一项基础但重要的功能。SSH(Struts、Spring、Hibernate)框架提供了便捷的方式来处理这一问题,无需依赖像 SmartUpload 或 ...

    jqueryUi+jqGrid+spring+hibernate+struts1.2+mysql 完美例子(带数据库文件)

    spring 2.0.1 ,hibernate3.0,strutd1.2,相关JAR包; 及c3p0-0.9.1.2.jar, mysql-connector-java-5.1.10-bin.jar 。 当时写的时候用的是JDK1.4,没有在JDK1.5下做测试,但在jdk1.5下应该没什么大问题,最多出现语法...

    Struts2+Spring2+Hibernate3+Annotation所需JAR包

    在Java Web开发领域,Struts2、Spring2和Hibernate3是三个非常重要的框架,它们分别负责Web层、业务逻辑层和服务持久化层的功能实现。为了更好地整合这三个框架,并利用注解(Annotation)简化配置,开发者通常需要...

    struts+spring+hibernate

    Struts2 是 Struts 的升级版本,它提供了更强大的功能和支持,如拦截器、类型转换以及文件上传等特性。通过使用 Struts2,开发者可以更好地分离业务逻辑和展示层,使得应用程序结构更加清晰。 ##### 1.2 Spring ...

    SSHF备忘之依赖包(struts2+spring2.5+hibernate+freemarker)

    5. **上传组件**:通常使用`commons-fileupload-1.2.jar`和`commons-io-1.3.2.jar`来处理文件上传功能。 6. **JSON处理**:`json-lib-2.0-jdk15.jar`用于解析和生成JSON格式的数据。 7. **JDBC驱动**:`jtds-1.2.2...

    基于struts+hibernate+spring银行开发的接口小系统

    综上所述,这个项目利用Struts、Hibernate和Spring构建了一个银行接口系统,通过JSON库处理数据交换,借助Commons IO库进行文件操作,使用Commons FileUpload库处理文件上传,并且使用Ajax技术优化用户界面的交互...

    struts2_spring3_hibernate3_1.2

    使用技术说明: 1.使用struts2+spring3+hibernate3整合实现用户CRUD功能。 2.使用技术 A.Struts2国际化(i18n)、本地化程序。...文件上传下载 C.DWR集成 D.Struts2异常处理 3.实现方式 基于配置文件

    Struts实现文件上传

    在Struts1.2版本中,实现文件上传是一项常见的需求,例如用户在网站上提交表单时可能需要上传图片、文档等文件。下面将详细解释如何使用Struts1.2实现文件上传功能,并涉及`fileForm`类型以及文件存储位置的相关知识...

    ssh框架实现上传上载

    写的比较简陋,,基于struts1.2+spring2.0+hibernate3.1框架 基本功能: 注册,登陆,validate框架验证,文件上传,下载,简单过滤器,权限限制,下载列表查看,下载历史记录查看 未处理中文,所有jar包...

    myeclipse5,tomcat5,struts1.2,servlet2.3,jsp2.0网上购物系统

    【标题】"myeclipse5,tomcat5,struts1.2,servlet2.3,jsp2.0网上购物系统" 提供了关于一个基于Java技术的电子商务平台开发的环境和框架信息。这个系统利用了MyEclipse 5作为集成开发环境(IDE),Tomcat 5作为应用...

Global site tag (gtag.js) - Google Analytics