Struts2+JDBC实现文件上传

Struts2文件上传原理图:

 

 

 

开发环境:eclipse+jdk1.8+mysql5.6+tomcat 7.0

项目搭建:(xml的配置这里不再细说,可以查看博主之前的博客)

mysql数据库:

CREATE TABLE `upload` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `uname` varchar(30) DEFAULT NULL,
  `uimg` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Util层:

DBConnection:

package cn.itstar.util;

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

public class DBConnection {

	private String driver = "com.mysql.jdbc.Driver";

	private String url = "jdbc:mysql://localhost:3306/test";

	private String user = "root";

	private String password = "root";

	private Connection conn = null;

	/**
	 * 连接数据库
	 * 
	 * @return
	 */
	public Connection getCon() {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public void closeAll(ResultSet rs, PreparedStatement pstm, Connection conn) {
		try {
			if(rs != null){
				rs.close();
			}if(pstm != null){
				pstm.close();
			}if(conn != null){
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

这里,我们自己编写一个文件重命名的方法:

MyChange:

package cn.itstar.util;
/**
 * 重命名
 */
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class MyChange {

	// 改名的方法
	public static String getMyNewName(String imgFileName) {

		String result = "";
		// 第一小步:得到原名的后缀(.jpg .txt)
		String lastname = imgFileName.substring(imgFileName.lastIndexOf("."));
		// 第二步:得到一个时间对象
		Date d = new Date();
		SimpleDateFormat ff = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = ff.format(d);
		// 第三步:得到一个随机数
		Random rad = new Random();
		int num = rad.nextInt(99999999);
		// 第四步:组装新名
		result = time + num + lastname;
		return result;
	}

}

 

实体类:

package cn.itstar.bean;
/**
 * 实体类
 */
import java.io.File;

public class Upload {
	private int uid;
	private String uname;
	private String uimg;
	
	
	
	//========================================================
	private File img;//得到文件上传对象
	private String  imgFileName;//得到上传文件的原名
	
	
	

	
	
	
	public File getImg() {
		return img;
	}

	public void setImg(File img) {
		this.img = img;
	}

	public String getImgFileName() {
		return imgFileName;
	}

	public void setImgFileName(String imgFileName) {
		this.imgFileName = imgFileName;
	}

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public String getUimg() {
		return uimg;
	}

	public void setUimg(String uimg) {
		this.uimg = uimg;
	}

}

dao层:

package cn.itstar.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import cn.itstar.bean.Upload;
import cn.itstar.util.DBConnection;

public class UploadDao {
	
	private Connection conn = null;
	private PreparedStatement pstm = null;
	private ResultSet rs = null;
	private DBConnection dbc;
	
	public UploadDao(){
		dbc = new DBConnection();
	}
	
	/**
	 * 全查询 
	 * @return
	 */
	public List<Upload> findAll(){
		List<Upload> ar = new ArrayList<Upload>();
		try {

			conn =dbc.getCon();
			String sql = "select * from upload";
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery();
			while (rs.next()) {
				Upload upload = new Upload();
				upload.setUid(rs.getInt("uid"));
				upload.setUimg(rs.getString("uimg"));
				upload.setUname(rs.getString("uname"));
				ar.add(upload);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			dbc.closeAll(rs, pstm, conn);
		}
		return ar;
	}
	
	/**
	 * 查询一个
	 * @param uid
	 * @return
	 */
	public Upload findByOne(int uid){
		Upload upload = new Upload();
		try {
			conn = dbc.getCon();
			String sql= "select * from upload where uid = ?";
			pstm = conn.prepareStatement(sql);
			pstm.setInt(1, uid);
			rs = pstm.executeQuery();
			while(rs.next()){
				upload.setUid(rs.getInt("uid"));
				upload.setUname(rs.getString("uname"));
				upload.setUimg(rs.getString("uimg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			dbc.closeAll(rs, pstm, conn);
		}
		return upload;
		
	}
	
	/**
	 * 添加
	 */
	public void addUpload(Upload upload){
		try {
			conn = dbc.getCon();
			String sql= "insert into upload values(null,?,?)";
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, upload.getUname());
			pstm.setString(2, upload.getUimg());
			pstm.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			dbc.closeAll(rs, pstm, conn);
		}
	}
	
	
	/**
	 * 修改
	 */
	public void uppUpload(Upload upload){
		try {
			conn = dbc.getCon();
			String sql= "update upload set uname = ?,uimg = ? where uid = ?";
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, upload.getUname());
			pstm.setString(2, upload.getUimg());
			pstm.setInt(3, upload.getUid());
			pstm.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			dbc.closeAll(rs, pstm, conn);
		}
	}
	
	/**
	 * 删除
	 */
	public void delUpload(int uid){
		try {
			conn = dbc.getCon();
			String sql= "delete from upload where uid = ?";
			pstm = conn.prepareStatement(sql);
			pstm.setInt(1, uid);
			pstm.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			dbc.closeAll(rs, pstm, conn);
		}
	}
}

Service接口层:

package cn.itstar.service;

import java.util.List;

import cn.itstar.bean.Upload;

public interface UploadService {
	// 全查询
	public List<Upload> findAll();

	// 查询一个
	public Upload findByOne(int uid);

	// 添加
	public void addUpload(Upload upload);

	// 修改
	public void uppUpload(Upload upload);

	// 删除
	public void delUpload(int uid);
}

Service层:

package cn.itstar.service.impl;

import java.util.List;

import cn.itstar.bean.Upload;
import cn.itstar.dao.UploadDao;
import cn.itstar.service.UploadService;

public class UploadServiceImpl implements UploadService{
	
	private UploadDao dao = new UploadDao();
	
	public List<Upload> findAll() {
		
		return this.dao.findAll();
	}

	
	public Upload findByOne(int uid) {
		
		return this.dao.findByOne(uid);
	}

	
	public void addUpload(Upload upload) {
		this.dao.addUpload(upload);
		
	}

	
	public void uppUpload(Upload upload) {
		this.dao.uppUpload(upload);
		
	}

	
	public void delUpload(int uid) {
		this.dao.delUpload(uid);
		
	}

}

action层:

package cn.itstar.action;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import cn.itstar.bean.Upload;
import cn.itstar.service.UploadService;
import cn.itstar.service.impl.UploadServiceImpl;
import cn.itstar.util.MyChange;

public class UploadAction {
	private UploadService uploadService = new UploadServiceImpl();
	private List<Upload> ar;
	private Upload upload;
	private int uid;

	public List<Upload> getAr() {
		return ar;
	}

	public void setAr(List<Upload> ar) {
		this.ar = ar;
	}

	public Upload getUpload() {
		return upload;
	}

	public void setUpload(Upload upload) {
		this.upload = upload;
	}

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public String findAll() {
		this.ar = this.uploadService.findAll();
		return "myall";
	}

	/**
	 * 查询一个
	 * 
	 * @return
	 */
	public String findByOne() {
		this.upload = this.uploadService.findByOne(uid);
		return "myone";
	}

	/**
	 * 添加
	 * 
	 * @return
	 */
	public String addUpload() {
		// 1.文件上传
		// 得到之前上传的路径
		String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("upload");
		// 改名字
		String newName = MyChange.getMyNewName(upload.getImgFileName());
		// 上传
		File f = new File(path, newName);

		try {
			FileUtils.copyFile(upload.getImg(), f);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 存入新名
		upload.setUimg(newName);

		// 2.存库
		this.uploadService.addUpload(upload);
		return this.findAll();
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	public String uppUpload() {
		// 得到之前上传的路径
		String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("upload");

		String x = null;
		x = upload.getImgFileName();
		if (x == null) {
			// 不修改图片

			// 得到原图片的名称
			Upload u = this.uploadService.findByOne(upload.getUid());
			String uimg = u.getUimg();

			// 封装
			upload.setUimg(uimg);

		} else {
			// 修改图片

			// 得到原图片的名称
			Upload u = this.uploadService.findByOne(upload.getUid());
			String uimg = u.getUimg();
			// 第一步:删除数据库上老的不要的图片
			File file = new File(path + "\\" + uimg);
			file.delete();

			// 第二步:上传
			String newName = MyChange.getMyNewName(upload.getImgFileName());
			File f = new File(path, newName);
			try {
				FileUtils.copyFile(upload.getImg(), f);
			} catch (IOException e) {
				e.printStackTrace();
			}

			// 第三步:新数据存库
			upload.setUimg(newName);

		}

		this.uploadService.uppUpload(upload);
		return this.findAll();
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String delUpload() {
		// 得到之前上传的路径
		String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("upload");
		// 得到原图片的名称
		Upload u = this.uploadService.findByOne(uid);
		String uimg = u.getUimg();

		// 删除数据库老的不要的图片
		// 第一步:删除数据库上老的不要的图片
		File file = new File(path + "\\" + uimg);
		file.delete();
		// 删除数据
		this.uploadService.delUpload(uid);
		return this.findAll();
	}

}

upload.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="upload" extends="struts-default" namespace="/">
		<action name="upload_*" method="{1}" class="cn.itstar.action.UploadAction">
			<result name="myall">/up/all.jsp</result>
			<result name="myone">/up/update.jsp</result>
		</action>
	</package>
</struts>

在struts.xml中引用upload.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>
		<include file="cn/itstar/xml/upload.xml"></include>
	</struts>

 

前台页面:

css部门:

mycss1.css

@CHARSET "UTF-8";
*{
	font-size: 12px;
}
td{
	border: 1px solid red;
	text-align: center;
	line-height: 25px;
}
table {
	border-collapse: collapse;
	width: 50%;
}

mycss2.css

@CHARSET "UTF-8";
*{
	font-size: 12px;
}
td{
	border: 1px solid red;
	line-height: 25px;
}
table {
	border-collapse: collapse;
	width: 50%;
}
.m{
	text-align: center;
}

jsp页面部分:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
	 <a href="${pageContext.request.contextPath }/upload_findAll.action">员工管理</a>
</body>
</html>

up/all.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
<link href="${pageContext.request.contextPath }/css/mycss1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
	<table align="center">
		<tr>
			<td>编号</td>
			<td>员工姓名</td>
			<td>相片</td>
			<td>修改</td>
			<td>删除</td>
		</tr>
		<s:iterator id="x" value="ar">
			<tr>
				<td>${x.uid }</td>
				<td>${x.uname }</td>
				<td><img src="${pageContext.request.contextPath }/upload/${x.uimg}" width="100" height="150" /></td>
				<td><a
					href="${pageContext.request.contextPath }/upload_findByOne.action?uid=${x.uid }">修改</a></td>
				<td><a
					href="${pageContext.request.contextPath }/upload_delUpload.action?uid=${x.uid }">删除</a></td>
			</tr>
		</s:iterator>

		<tr>
			<td colspan="5" align="center"> 
			
			   <a
					href="${pageContext.request.contextPath }/up/add.jsp">增加员工 </a>
			</td>
		</tr>
	</table>
</body>
</html>

up/add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
<link href="${pageContext.request.contextPath }/css/mycss2.css"
	rel="stylesheet" type="text/css" />
</head>
<body>
	<s:form action="upload_addUpload.action" method="post" theme="simple" enctype="multipart/form-data">
		<table align="center">
			<tr>
				<Td class="m">姓名:</Td>
				<td><s:textfield name="upload.uname"></s:textfield></td>
			</tr>
			<tr>
				<Td class="m">相片:</Td>
				<td>
				  <s:file name="upload.img"></s:file>
				</td>
			</tr>
			<tr>
				
				<td colspan="2" align="center">
				    <s:submit value="确定"></s:submit>
				</td>
			</tr>
		</table>
	</s:form>
</body>
</html>

 

up/update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
<link href="${pageContext.request.contextPath }/css/mycss2.css"
	rel="stylesheet" type="text/css" />
</head>
<body>
	<s:form action="upload_uppUpload.action" method="post" theme="simple" enctype="multipart/form-data">
		<table align="center">
			<tr>
				<Td class="m">姓名:</Td>
				<td><s:textfield name="upload.uname"></s:textfield></td>
			</tr>
			<tr>
				<Td class="m">相片:</Td>
				<td>
				  <s:file name="upload.img"></s:file>
				</td>
			</tr>
			<s:hidden name="upload.uid"></s:hidden>
			<tr>
				
				<td colspan="2" align="center">
				    <s:submit value="确定"></s:submit>
				</td>
			</tr>
		</table>
	</s:form>
</body>
</html>

项目运行:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值