在struts2框架中,要遵循约定大于配置,下面是一个文件上传于下载的小例子,记下来以备忘
1.file数据库(用的数据库为mysql)
里面只有一张t_file表
id: int 主键
name: varchar
size: float
contentType : varchar
2.upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="upload.action" method="post" enctype="multipart/form-data" >
文件名称:<input type="text" name="desc"/><br/>
请选择文件: <input type="file" name="doc"/><br/>
<input type="submit" value="上传"/>
</form>
<br />
<br />
<table border = "1" width="70%">
<tr>
<th>文件名</th>
<th>大小</th>
<th>操作</th>
</tr>
<c:forEach items="${list }" var = "file">
<tr>
<td>${file.name }</td>
<td>${file.size }</td>
<td>
<a href="download.action?id=${file.id }">下载</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:///file
name=root
pwd=root
4. struts.properties
struts.multipart.saveDir:为文件在磁盘上缓存的位置
struts.multipart.maxSize:为上传文件的最大值,单位为B
struts.action.extension=action
struts.multipart.saveDir=C:/temp
struts.multipart.maxSize=20971520
5. struts2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="mypackage" extends="struts-default" >
<action name="file" class="com.kaishengit.action.FileAction">
<result>/WEB-INF/views/upload.jsp</result>
</action>
<action name="upload" class="com.kaishengit.action.FileAction" method="upload">
<result type="redirectAction">
<param name="actionName">file</param>
</result>
</action>
<action name="download" class="com.kaishengit.action.FileAction" method="download">
<result name="success" type="stream">
<param name="contentType">${contentType}</param>
<param name="contentLength">${fileSize}</param>
<param name="inputName">mystream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
package com.kaishengit.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import com.kaishengit.entity.Document;
import com.kaishengit.service.DocumentService;
import com.opensymphony.xwork2.Action;
public class FileAction implements Action{
//约定大于配置
private String desc;
private File doc;
private String docFileName; //文件的名字,根据表单中file的name是doc,在doc后加上FileName就是所上传文件的实际的名字,约定大于配置
private String docContentType; //同上
private List<Document> list;
private String id;
private String contentType;
private long fileSize;
private String fileName;
DocumentService ds = new DocumentService();
public String execute() throws Exception {
list = ds.findAll();
return SUCCESS;
}
public String upload() throws Exception {
System.out.println(desc);//得到的是输入的文件名
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(doc));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:/upload",docFileName)));
byte[] buffer = new byte[512];
int len = -1;
while((len = bis.read(buffer)) != -1) {
bos.write(buffer,0,len);
}
//千万不要忘记flush 和 close
bos.flush();
bos.close();
bis.close();
ds.save(docFileName,doc.length(),docContentType);
return SUCCESS;
}
public String download() {
return SUCCESS;
}
public InputStream getMystream() throws FileNotFoundException {
Document d = ds.findById(id);
File file = new File("C:/upload",d.getName());
fileSize = d.getSize();
contentType = d.getContentType();
fileName = d.getName();
return new FileInputStream(file);
}
//get set
public List<Document> getList() {
return list;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setList(List<Document> list) {
this.list = list;
}
public File getDoc() {
return doc;
}
public void setDoc(File doc) {
this.doc = doc;
}
public String getDocFileName() {
return docFileName;
}
public void setDocFileName(String docFileName) {
this.docFileName = docFileName;
}
public String getDocContentType() {
return docContentType;
}
public void setDocContentType(String docContentType) {
this.docContentType = docContentType;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
7. Document.java
package com.kaishengit.entity;
public class Document {
private int id;
private String name;
private long size;
private String contentType;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
8. DocumentService.java
package com.kaishengit.service;
import java.util.List;
import com.kaishengit.dao.DocumentDao;
import com.kaishengit.entity.Document;
public class DocumentService {
DocumentDao dao = new DocumentDao();
public List<Document> findAll() {
return dao.findAll();
}
public void save(String docFileName, long length, String docContentType) {
Document d = new Document();
d.setContentType(docContentType);
d.setName(docFileName);
d.setSize(length);
dao.save(d);
}
public Document findById(String id) {
return dao.findById(id);
}
}
package com.kaishengit.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.kaishengit.entity.Document;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;
public class DocumentDao {
DBHelp<Document> db = new DBHelp<Document>();
public List<Document> findAll() {
final String sql = "SELECT id,`name`,size,contentType FROM t_file";
return db.executeQueryForList(sql, new DocumentRowMapper());
}
private class DocumentRowMapper implements RowMapper<Document>{
public Document mapRow(ResultSet rs) throws SQLException {
Document d = new Document();
d.setContentType(rs.getString("contentType"));
d.setId(rs.getInt("id"));
d.setName(rs.getString("name"));
d.setSize(rs.getLong("size"));
return d;
}
}
public void save(Document d) {
final String sql = "INSERT INTO t_file(`name`,size,contentType) VALUES(?,?,?)";
db.executeSQL(sql, d.getName(),d.getSize(),d.getContentType());
}
public Document findById(String id) {
final String sql = "SELECT id,`name`,size,contentType FROM t_file where id=?";
return db.executeQueryForObject(sql, new DocumentRowMapper(), id);
}
}
10.DBHelp.java
package com.kaishengit.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
/**
* 访问数据库的工具类
*
*/
public class DBHelp<T> {
private static BasicDataSource ds;
static{
InputStream stream = DBHelp.class.getClassLoader().getResourceAsStream("db.properties");
Properties p = new Properties();
try {
p.load(stream);
ds = new BasicDataSource();
ds.setUrl(p.getProperty("url"));
ds.setPassword(p.getProperty("pwd"));
ds.setDriverClassName(p.getProperty("driver"));
ds.setUsername(p.getProperty("name"));
ds.setInitialSize(5);
ds.setMaxActive(20);
ds.setMaxWait(5000);
ds.setMinIdle(8);
System.out.println("数据源创建完成...........................");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
* @return Connection类的对象
*/
public Connection getConnection() {
Connection conn =null;
try {
conn = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public List<T> executeQueryForList(String sql,RowMapper<T> rm,Object...args) {
Connection conn = null;
PreparedStatement stat = null;
ResultSet rs = null;
List<T> list = new ArrayList<T>();
try {
conn = getConnection();
stat = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
stat.setObject(i+1, args[i]);
}
rs = stat.executeQuery();
while(rs.next()) {
T obj = rm.mapRow(rs);
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(rs, stat, conn);
}
return list;
}
public Object executeQueryForFunction(String sql,Object...args) {
Connection conn = null;
PreparedStatement stat = null;
ResultSet rs = null;
Object result = null;
try {
conn = getConnection();
stat = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
stat.setObject(i+1, args[i]);
}
rs = stat.executeQuery();
if(rs.next()) {
result = rs.getObject(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(rs,stat,conn);
}
return result;
}
public T executeQueryForObject(String sql,RowMapper<T> rm,Object...args) {
Connection conn = null;
PreparedStatement stat = null;
ResultSet rs = null;
T obj = null;
try {
conn = getConnection();
stat = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
stat.setObject(i+1, args[i]);
}
rs = stat.executeQuery();
if(rs.next()) {
obj = rm.mapRow(rs);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(rs, stat, conn);
}
return obj;
}
/**
* 执行insert update delete语句
* @param sql insert or update or delte语句
* @return true代表成功 false代表失败
*/
public boolean executeSQL(String sql,Object... args) {
Connection conn = null;
PreparedStatement stat = null;
try {
conn = getConnection();
stat = conn.prepareStatement(sql);
//?
for (int i = 0; i < args.length; i++) {
stat.setObject(i + 1, args[i]);
}
int rows = stat.executeUpdate();
if(rows > 0) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(stat,conn);
}
return false;
}
/**
* 释放数据库资源
* @param rs
* @param stat
* @param conn
*/
public void close(ResultSet rs, Statement stat, Connection conn) {
try {
if(rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(stat != null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
* 释放数据库资源
* @param stat
* @param conn
*/
public void close(Statement stat,Connection conn) {
close(null,stat,conn);
}
}
11.RowMapper.java
package com.kaishengit.util;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface RowMapper<T> {
public T mapRow(ResultSet rs) throws SQLException;
}