【Struts 文件上传下载】
RegisterAction
package k.action; import k.domain.User;
import k.form.UserForm;
import k.service.UserService;
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.upload.FormFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID; public class RegisterAction extends DispatchAction {
public ActionForward fileUpload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm dynaForm = (UserForm) form;
String userName = dynaForm.getUserName();
FormFile formFile = dynaForm.getMyPhoto();
String oldFileName = formFile.getFileName();
System.out.println("==" + userName + "==" + oldFileName + "==" + formFile.getFileSize());
String path = this.getServlet().getServletContext().getRealPath("/file"); File file = new File(path);
if (!file.exists())
file.mkdir();
String newfileName = getNewFileName(oldFileName);
String newpath = path + "\\" + newfileName;
InputStream inputStream = null;
FileOutputStream outputStream = null;
byte[] bytes = new byte[1024];
int len;
try {
inputStream = formFile.getInputStream();
outputStream = new FileOutputStream(newpath);
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
}
User user = new User("", userName, formFile.getFileName(), newfileName);
System.out.println(user);
if (new UserService().addUser(user)) {
return mapping.findForward("registerOk");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
}
return mapping.findForward("err");
} private static String getNewFileName(String fileName) {
int beginIndex = fileName.lastIndexOf(".");
return UUID.randomUUID().toString() + fileName.substring(beginIndex, fileName.length());
} public ActionForward getUserList(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UserService userService = new UserService();
List<Map<String, Object>> userList = userService.getUserList();
ArrayList<User> userArrayList = new ArrayList<>();
for (Map<String, Object> item : userList) {
String id = item.get("id").toString();
String username = item.get("user_name").toString();
String photo_old_name = item.get("photo_old_name").toString();
String photo_new_name = item.get("photo_new_name").toString();
User user = new User(id, username, photo_old_name, photo_new_name);
userArrayList.add(user);
}
request.setAttribute("userList", userArrayList);
return mapping.findForward("listUser");
} public ActionForward downUserPhoto(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
User user = new User();
user.setId(request.getParameter("id"));
UserService userService = new UserService();
List<Map<String, Object>> userList = userService.getUser(user); String photo_old_name = userList.get(0).get("photo_old_name").toString();
String photo_new_name = userList.get(0).get("photo_new_name").toString();
String path = this.getServlet().getServletContext().getRealPath("/file"); response.setContentType("text/html; charset=utf-8");
String urlFileName = URLEncoder.encode(photo_old_name, "utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + urlFileName); InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(path + "\\" + photo_new_name);
outputStream = response.getOutputStream();
int len;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
}
return mapping.findForward("listUser");
}
}
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>注册页面</h1>
<form action="${APP_PATH}/register.do?action=fileUpload" method="post" enctype="multipart/form-data">
名字:<input type="text" name="userName" value="11哈哈"> <br>
头像: <input type="file" name="myPhoto"> <br>
<input type="submit" value="submit"> <br>
</form>
</body>
</html>
listUser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
<title>error</title>
</head>
<body>
<h1>用户列表</h1>
<c:forEach items="${userList}" var="user">
用户名:${user.userName}
<img src="${APP_PATH}/file/${user.photoNewName}" width="300px">
<a href="${APP_PATH}/register.do?action=downUserPhoto&id=${user.id}">点击下载</a>
<br>
</c:forEach>
</body>
</html>
registerOk.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册成功</h1>
<a href="${APP_PATH}/register.do?action=getUserList">用户列表</a>
</body>
</html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<jsp:forward page="WEB-INF/jsp/register.jsp"></jsp:forward>
</body>
</html>
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<global-forwards>
<forward name="err" path="/WEB-INF/jsp/err.jsp" redirect="false"></forward>
</global-forwards>
<form-beans>
<form-bean name="userForm" type="k.form.UserForm">
<form-property name="userName" type="java.lang.String"></form-property>
<form-property name="myphoto" type="org.apache.struts.upload.FormFile"></form-property>
</form-bean>
</form-beans>
<action-mappings>
<action name="userForm" path="/register" parameter="action" type="k.action.RegisterAction"
scope="request" attribute="userForm" input="index.jsp" validate="false">
<forward name="registerOk" path="/WEB-INF/jsp/registerOk.jsp"></forward>
<forward name="listUser" path="/WEB-INF/jsp/listUser.jsp"></forward>
</action>
</action-mappings>
</struts-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<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>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>k.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <listener>
<display-name>StartSystemListener</display-name>
<listener-class>k.filter.StartSystemListener</listener-class>
</listener>
</web-app>
User
package k.domain; public class User {
private String id; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} private String userName;
private String photoOldName; public User(String id, String userName, String photoOldName, String photoNewName) {
this.id = id;
this.userName = userName;
this.photoOldName = photoOldName;
this.photoNewName = photoNewName;
} public String getPhotoNewName() { return photoNewName;
} public void setPhotoNewName(String photoNewName) {
this.photoNewName = photoNewName;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPhotoOldName() {
return photoOldName;
} public void setPhotoOldName(String photoOldName) {
this.photoOldName = photoOldName;
} private String photoNewName; public User() {
}
}
EncodingFilter
package k.filter; import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import java.io.IOException; public class EncodingFilter extends HttpServlet implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
// System.out.println("========== set utf-8 ok ==========");
filterChain.doFilter(servletRequest, servletResponse);
} @Override
public void init(FilterConfig filterConfig) throws ServletException { }
}
StartSystemListener
package k.filter; import k.utils.WebHelper; import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; public class StartSystemListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//1.将项目上下文路径(request.getContextPath())放置到application域中.
ServletContext application = sce.getServletContext();
String app_path = application.getContextPath();
application.setAttribute("APP_PATH", app_path);
System.out.println("========== APP_PATH = " + app_path);
WebHelper.setApp_Path(app_path);
} @Override
public void contextDestroyed(ServletContextEvent sce) { }
}
UserForm
package k.form; import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile; public class UserForm extends ActionForm {
private String userName;
private FormFile myPhoto; public UserForm() {
} public UserForm(String userName, FormFile myPhoto) { this.userName = userName;
this.myPhoto = myPhoto;
} public String getUserName() { return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public FormFile getMyPhoto() {
return myPhoto;
} public void setMyPhoto(FormFile myPhoto) {
this.myPhoto = myPhoto;
}
}
UserService
package k.service; import k.domain.User;
import k.utils.JdbcUtils; import java.util.List;
import java.util.Map; public class UserService {
public boolean addUser(User user) {
String sql = "insert into user_photo (user_name,photo_old_name,photo_new_name) VALUES(?,?,?);";
Object[] parms = new Object[]{user.getUserName(), user.getPhotoOldName(), user.getPhotoNewName()};
int a1 = JdbcUtils.executeUpdate(sql, parms);
return a1 == 1;
} public List<Map<String, Object>> getUserList() {
String sql = "SELECT id,user_name,photo_old_name,photo_new_name FROM user_photo;";
List<Map<String, Object>> maps = JdbcUtils.executeQuery(sql);
return maps;
} public List<Map<String, Object>> getUser(User user) {
String sql = "SELECT id,user_name,photo_old_name,photo_new_name FROM user_photo where id=?;";
Object[] parms = new Object[]{user.getId()};
List<Map<String, Object>> maps = JdbcUtils.executeQuery(sql, parms);
return maps;
}
}
JdbcUtils
package k.utils; import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public final class JdbcUtils {
private static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
private static String user = "root";
private static String password = "xxxxxx"; public static void main(String[] args) {
// String sql = "UPDATE `user` set money=money+10 WHERE `name` =? ";
// Object[] parms = new Object[]{"name1"};
// int a1 = executeUpdate(sql, parms);
// System.out.println(a1);
String sql = "select * from user";
List<Map<String, Object>> list = executeQuery(sql, null);
for (Map<String, Object> map : list) {
for (String key : map.keySet()) {
System.out.println("Key=" + key + "\t value=" + map.get(key));
}
System.out.println();
}
} public static List<Map<String, Object>> executeQuery(String sql) {
return executeQuery(sql, null);
} public static List<Map<String, Object>> executeQuery(String sql, Object[] parms) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
conn = JdbcUtils.getConnection();
st = conn.prepareStatement(sql);
if (parms != null && parms.length > 0) {
for (int i = 0; i < parms.length; i++) {
st.setObject(i + 1, parms[i]);
}
}
rs = st.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
String columnLabel = rsmd.getColumnLabel(i + 1);
Object columnValue = rs.getObject(columnLabel);
map.put(columnLabel, columnValue);
}
list.add(map);
} } catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.free(rs, st, conn);
}
return list;
} public static int executeUpdate(String sql, Object[] parms) {
int res = -1;
Connection conn = null;
PreparedStatement pst = null;
ResultSet set = null;
try {
conn = getConnection();
pst = conn.prepareStatement(sql);
for (int i = 0; i < parms.length; i++) {
pst.setObject(i + 1, parms[i]);
}
res = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
free(set, pst, conn);
}
return res;
} private JdbcUtils() {
} static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
} public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
} public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
WebHelper
package k.utils; import java.util.UUID; public class WebHelper { public static String getApp_Path() {
return APP_PATH;
} public static void setApp_Path(String appPath) {
APP_PATH = appPath;
} private static String APP_PATH = ""; public static String getNewFileName(String fileName) {
int beginIndex = fileName.lastIndexOf(".");
return UUID.randomUUID().toString() + fileName.substring(beginIndex, fileName.length());
}
}
【Struts 文件上传下载】的更多相关文章
- struts 文件上传下载
上传 1.编写上传action类 UploadAction.java package jxf.b_upload; import java.io.File; import java.io.IOExcep ...
- Struts文件上传下载
Struts配置文件: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PU ...
- Struts的文件上传下载
Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...
- ssh框架文件上传下载
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- JAVA Web 之 struts2文件上传下载演示(二)(转)
JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...
- JAVA Web 之 struts2文件上传下载演示(一)(转)
JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...
- 2013第38周日Java文件上传下载收集思考
2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...
- Struts2 控制文件上传下载
之前介绍servlet3.0新特性的时候有提到过servlet API提供了一个part类来实现对文件的上传和保存,Struts其实是在其基础上做了进一步的封装,更加简单易用.至于文件下载,Strut ...
随机推荐
- linq和扩展方法
c#的扩展方法 1.必须是在一个非嵌套.非泛型的静态类中的静态方法 2.至少一个参数,第一个参数附加this,不能有其他修饰符如out.ref 3.第一个参数不能是指针类型 上面例子是自定义的一个扩展 ...
- html5 标准文档结构
<!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset=" ...
- util之Queue
定义:ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); offer();添加元素 Peek()返回队列首部元素值 P ...
- PLL
PLL(Phase Locked Loop): 为锁相回路或锁相环,用来统一整合时脉讯号,使内存能正确的存取资料.PLL用于振荡器中的反馈技术. 许多电子设备要正常工作,通常需要外部的输入信号与内部的 ...
- python写excel总结
废话不说,直接上代码:import xlrd import xlwt # 读excel然后写到mysql的套路def updata_info(): book = xlrd.open_workbook( ...
- 图的最小生成树prim算法模板
用prim算法构建最小生成树适合顶点数据较少而边较多的图(稠密图) prim算法生成连通图的最小生成树模板伪代码: G为图,一般为全局变量,数组d为顶点与集合s的最短距离 Prim(G, d[]){ ...
- testng实现代码和数据分层
todo: 参考: https://www.cnblogs.com/znicy/p/6534893.html
- Tomcat配置过程
Tomcat的配置其实还是挺简单的,下面是在Myeclipse中配置 1.首先要在Tomcat官网下载,网址:http://tomcat.apache.org/,然后左侧会有Download,选择你要 ...
- Dev-Cpp/Code::Block/MinGW下使用EasyX
众所周知,EasyX是个很香的东西,但EasyX目前只支持Visual Studio,那么如果要在MinGW(Dev-Cpp和Code::Block均使用这个编译器)上使用EasyX怎么办呢? 这篇文 ...
- EntityFramework使用SqlCe数据库
使用NuGet添加下面3个引用 App.Config的<entityFramework>节点这样配置: <entityFramework> <defaultConnect ...