您的位置:首页 > 其它

3.8拦截器和文件上传下载

2018-03-03 11:05 197 查看
(1)拦截器登录实例
(2)自定义UI模板
(3)文件上传和下载(下载中有一部分内容是3.11中的)

1:自定义UI模板步骤
    WebContent\WEB-INF\lib\struts2-core-2.3.28.jar\template.simple下找要修改的相应标签
    a:在src目录下新建一个文件夹:template
    b:在template目录下新建一个自定义模板的文件夹名称:例my_theme
    c:在my_theme中定义新的模板文件。

    d:在标签中通过theme属性来引用新的的模板。
2:文件的上传和下载
    a:包括用servlet方式的上传和下载(文件存在数据库中和只在数据库中存储文件路径两种方式)
    b:用struts中的下载方式

    c:代码:

    main.jsp

    
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<pre>
系统主页面

<a href="<%=path%>/upload_folder.jsp">1:文件上传到文件夹中</a>

<a href="<%=path%>/upload_table.jsp">2:文件上传到表中</a>

<a href="<%=path%>/downloadAction!list">3:下载列表页面</a>

</pre>
</body>
</html>    upload_folder.jsp
    
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<pre>
1:文件上传到文件夹中

前提:
1:表单中加入enctype="multipart/form-data":表单是以流的方式来提交。

2:工程中要加入文件上传的2个jar包。commons-fileupload-1.3.1.jar/commons-io-2.2.jar

3:struts.xml常量配置上传的大小。struts.multipart.maxSize

<s:form method="post" action="uploadAction!save_folder"
enctype="multipart/form-data">

id:<s:textfield name="id" id="id" />

testname:<s:textfield name="testname" id="testname" />

testimage:<s:file name="testimage" id="testimage" />

<input type="submit" value="上传到文件夹中" />

</s:form>

</pre>
</body>
</html>    upload_table.jsp
    
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<pre>
1:文件上传到表中

前提:
1:表单中加入enctype="multipart/form-data":表单是以流的方式来提交。

2:工程中要加入文件上传的2个jar包。commons-fileupload-1.3.1.jar/commons-io-2.2.jar

3:struts.xml常量配置上传的大小。struts.multipart.maxSize

4:表中的字段必须为image字段类型。

<s:form method="post" action="uploadAction!save_table"
enctype="multipart/form-data">

id:<s:textfield name="id" id="id" />

testname:<s:textfield name="testname" id="testname" />

testimage:<s:file name="testimage" id="testimage" />

<input type="submit" value="上传到table中" />

</s:form>

</pre>
</body>
</html>    UploadAction.java
    
package com.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.bean.UserBean;
import com.util.BaseAction;
import com.util.Global;
import com.util.JdbcUtil;

public class UploadAction extends BaseAction {

@Override
public String execute() throws Exception {
return null;
}

/**
* 上传到文件夹中
*
* @return
* @throws Exception
*/
private String id;
private String testname;
private File testimage;
//下面的两个命名要和上面那个testimage相对应
private String testimageFileName;
private String testimageContentType;

public String getId() {
return id;
}

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

public String getTestname() {
return testname;
}

public void setTestname(String testname) {
this.testname = testname;
}

public File getTestimage() {
return testimage;
}

public void setTestimage(File testimage) {
this.testimage = testimage;
}

public String getTestimageFileName() {
return testimageFileName;
}

public void setTestimageFileName(String testimageFileName) {
this.testimageFileName = testimageFileName;
}

public String getTestimageContentType() {
return testimageContentType;
}

public void setTestimageContentType(String testimageContentType) {
this.testimageContentType = testimageContentType;
}

public String save_folder() throws Exception {
System.out.println("id = " + id);
System.out.println("testname = " + testname);
System.out.println("testimage = " + testimage);
System.out.println("testimageFileName = " + testimageFileName);
System.out.println("testimageContentType = " + testimageContentType);

/*
*这个的前提是创建一个叫system.properties的文件
*里面的值为upload.dir=E:\\upload_files
*
* */
Properties properties = new Properties();
properties.load(UploadAction.class
.getResourceAsStream("/system.properties"));

String upload_dir = String
.valueOf(properties.getProperty("upload.dir"));

String filepath = Global.getSysTimeStamp() + "_"
+ this.testimageFileName;
/**
* 上传到文件夹中
*/
File destFile = new File(upload_dir + "\\" + filepath);
FileUtils.copyFile(this.testimage, destFile);

/**
* 写到数据库中
*/
StringBuffer insertSQL = new StringBuffer();
insertSQL.append("Insert into T_TestLob");
insertSQL.append("(testname,filename,filepath");
insertSQL.append(") values(");
insertSQL.append("'" + testname + "'");
insertSQL.append(",'" + this.testimageFileName + "'");
insertSQL.append(",'" + filepath + "'");
insertSQL.append(")");

System.out.println(insertSQL.toString());
try {
JdbcUtil.executeUpdate(insertSQL.toString());
} catch (Exception e) {
e.printStackTrace();
}

return null;
}

public String save_table() throws Exception {
/**
* 写到数据库中
*/
StringBuffer insertSQL = new StringBuffer();
insertSQL.append("Insert into T_TestLob");
insertSQL.append("(testname,filename,filedata");
insertSQL.append(") values(");
insertSQL.append("?,?,?");
insertSQL.append(")");
Connection conn = null;
PreparedStatement pstmt = null;

try {
InputStream inputStream = new FileInputStream(this.testimage);

conn = JdbcUtil.getConn();
pstmt = conn.prepareStatement(insertSQL.toString());
pstmt.setString(1, this.testname);
pstmt.setString(2, this.testimageFileName);
//因为是文件,所以得用二进制流
pstmt.setBinaryStream(3, inputStream, (long)this.testimage.length());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.closeResource(pstmt, conn);
}
System.out.println("文件上传到数据库已完成");
return null;
}

}
    struts.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>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<constant name="struts.multipart.maxSize" value="209715200"></constant>
<constant name="struts.action.extension" value="action,,"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.configuration.xml.reload" value="true"></constant>
<constant name="struts.i18n.reload" value="true"></constant>
<constant name="struts.ui.theme" value="simple"></constant>
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>

<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="isLogin" class="com.interceptor.IsLoginInterceptor"></interceptor>
<interceptor-stack name="myStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<!--
<interceptor-ref name="isLogin"></interceptor-ref>
-->
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<action name="loginAction" class="com.action.LoginAction">
<result name="login">/login.jsp</result>
<result name="main">/main.jsp</result>
</action>

<action name="uploadAction" class="com.action.UploadAction">
</action>

<action name="downloadAction" class="com.action.DownloadAction">
<result name="download_list">/download_list.jsp</result>
<result name="download_struts" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="bufferSize">10240</param>
<param name="contentDisposition">attachment;filename=${yyy_name}</param>
<!-- 表示调用Action中getXxx的方法。 -->
<param name="inputName">xxx</param>
</result>
</action>

</package>
</struts>
    DownLoadAction.java
    
package com.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.opensymphony.xwork2.ActionContext;
import com.util.BaseAction;
import com.util.JdbcUtil;
import com.util.PropUtil;

public class DownloadAction extends BaseAction {

@Override
public String execute() throws Exception {
return null;
}

public String list() throws Exception {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "Select id,testname,filename,filepath From T_TestLob order by id desc";
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
try {
conn = JdbcUtil.getConn();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
Map<String, Object> rowMap = new HashMap<String, Object>();

int id = rs.getInt("id");
String testname = rs.getString("testname");
String filename = rs.getString("filename");
String filepath = rs.getString("filepath");

rowMap.put("id", id);
rowMap.put("testname", testname);
rowMap.put("filename", filename);
rowMap.put("filepath", filepath);

dataList.add(rowMap);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.closeResource(rs, stmt, conn);
}
ActionContext context = ActionContext.getContext();
context.put("dataList", dataList);

session.setAttribute("str", "Session作用域中的数据");
return "download_list";
}

/**
* 从文件夹中下载
*
* @return
* @throws Exception
*/
public String download_folder() throws Exception {
String id = request.getParameter("id");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "Select filename,filepath From T_TestLob where id = " + id
+ "";
String filename = null;
String filepath = null;
try {
conn = JdbcUtil.getConn();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
filename = rs.getString("filename");
filepath = rs.getString("filepath");
}
if (filepath != null && !filepath.equals("")) {
String upload_dir = PropUtil.getValue("upload.dir");
File downloadFile = new File(upload_dir + "\\" + filepath);
if (downloadFile.exists() == true) {
/**
* 下载文件。
*/
response.setContentType("application/octet-stream");

String encode_filename = new String(
filename.getBytes("GBK"), "ISO-8859-1");

response.setHeader("Content-Disposition",
"attachment;filename=\"" + encode_filename + "\"");

InputStream inputStream = new FileInputStream(downloadFile);
//这里要注意用的是response中的输出流,输出到页面
OutputStream outputStream = response.getOutputStream();

IOUtils.copy(inputStream, outputStream);

IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.closeResource(rs, stmt, conn);
}
return null;
}

public String download_table() throws Exception {
String id = request.getParameter("id");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "Select filename,filedata From T_TestLob where id = " + id
+ "";
String filename = null;
InputStream filedata = null;
try {
conn = JdbcUtil.getConn();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
filename = rs.getString("filename");
//用二进制流来接收
filedata = rs.getBinaryStream("filedata");
}
if (filename != null && !filename.equals("")) {
if (filedata.available() > 0) {
/**
* 下载文件。
*/
response.setContentType("application/octet-stream");

String encode_filename = new String(
filename.getBytes("GBK"), "ISO-8859-1");

response.setHeader("Content-Disposition",
"attachment;filename=\"" + encode_filename + "\"");
OutputStream outputStream = response.getOutputStream();

IOUtils.copy(filedata, outputStream);
IOUtils.closeQuietly(filedata);
IOUtils.closeQuietly(outputStream);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.closeResource(rs, stmt, conn);
}
return NONE;
}

/**
* 使用Struts的方式来进行下载
*
* @return
* @throws Exception
*/
//这里的名字要与struts.xml中的配置一致
private InputStream xxx;
private String yyy_name;

public InputStream getXxx() throws Exception {
System.out.println("getXXXX这个方法");
return xxx;
}

public String getYyy_name() {
System.out.println("调用到getYyy_name这个方法");
return yyy_name;
}

public String download_struts() throws Exception {
String id = request.getParameter("id");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "Select filename,filepath From T_TestLob where id = " + id
+ "";
String filename = null;
String filepath = null;
try {
conn = JdbcUtil.getConn();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
filename = rs.getString("filename");
filepath = rs.getString("filepath");

}
if (filepath != null && !filepath.equals("")) {
String upload_dir = PropUtil.getValue("upload.dir");
File downloadFile = new File(upload_dir + "\\" + filepath);
if (downloadFile.exists() == true) {
//这种下载方式解决不了名字中的空格问题,所以采用替代的方法。
filename = filename.replaceAll(" ", "_");

String encode_filename = new String(
filename.getBytes("GBK"), "ISO-8859-1");
this.yyy_name = encode_filename;
InputStream inputStream = new FileInputStream(downloadFile);
this.xxx = inputStream;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.closeResource(rs, stmt, conn);
}

return "download_struts";
}
}
    download_list.jsp
    
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<pre>
%{}符号的使用:

表示将%{},花括号中的内容解析为OGNL表达式,并且输出。
str = <s:property value="#session.str"/>

<s:textfield name="aaa" value="%{#session.str}"/>
</pre>
文件下载列表页面

<table width="100%" border="1" style="font-size:12px;">
<tr>
<td>id</td>
<td>testname</td>
<td>filename</td>
<td>filepath</td>
<td colspan="2">下载</td>
</tr>
<s:iterator value="#dataList">
<tr>
<td><s:property value="id"/> </td>
<td><s:property value="testname"/></td>
<td><s:property value="filename"/></td>
<td><s:property value="filepath"/></td>
<td>
<s:if test="filepath != null && filepath != ''">
<a href="<%=path%>/downloadAction!download_folder?id=<s:property value="id"/>">文件夹下载</a>
<a href="<%=path%>/downloadAction!download_struts?id=<s:property value="id"/>">struts下载</a>
</s:if>
</td>
<td>
<s:if test="filepath == null || filepath == ''">
<a href="<%=path%>/downloadAction!download_table?id=<s:property value="id"/>">表中下载</a>
</s:if>
</td>
</tr>
</s:iterator>
</table>

</body>
</html>d:后面是一些辅助代码
JdbcUtil.javapackage com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JdbcUtil {
private static String driverClass = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/text?useUnicode=true&characterEncoding=UTF-8";

private static String username = "root";
private static String password = "";

static {
try {
Class.forName(driverClass);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("无法加载数据库的驱动");
}

}

public static Connection getConn() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}

return conn;
}

public static int executeUpdate(String sql) throws Exception {
Connection conn = null;
Statement stmt = null;
System.out.println(url);
try {
conn = getConn();
stmt = conn.createStatement();
return stmt.executeUpdate(sql);

} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
closeResource(stmt, conn);
}
}

public static void closeResource(Statement stmt, Connection conn) {
closeResource(null, stmt, conn);
}

public static void closeResource(ResultSet rs, Statement stmt,
Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
    PropUtil.javapackage com.util;

import java.util.Properties;

public class PropUtil {
private static Properties properties = new Properties();
static {
try {
properties.load(PropUtil.class
.getResourceAsStream("/syssource.properties"));
} catch (Exception e) {
e.printStackTrace();
}
}

public static String getValue(String key) {
String value = "";
try {
value = properties.getProperty(key);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
e:数据库结构

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: