struts1.2 + Hibernate3实现文件下传上载与其他操作
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;
}}