新增商品功能的實現
Jsp頁面設定:
<formaction="${pageContext.request.contextPath}/AddProdServlet" method="post" enctype="multipart/form-data">
</form>
Servlet相關操作:
//因為要傳表單中的名稱,以及值,所以建立map進行存放
Map<String, String> map = new HashMap<String, String>();
// 建立DiskFileItemFactory物件,設定緩衝區大小和臨時檔案目錄
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*100);
factory.setRepository(new File(this.getServletContext()
.getRealPath("/WEB-INF/tmp")));
// 使用DiskFileItemFactory 物件建立ServletFileUpload物件,並設定上傳檔案的大小限制。
ServletFileUpload fileUpload = new
//檢查是否是正確的檔案上傳表單
if(!fileUpload.isMultipartContent(request))
{
throw new RuntimeException("請用正確的表單進行上傳");
}
//設定單個檔案上傳的大小:
fileUpload.setFileSizeMax(1024 * 10204 * 5);
//設定檔案上傳的總大小:
fileUpload.setSizeMax(1024 * 10204 * 200);
//對上傳的內容進行解析
List<FileItem> list
//遍歷上傳的檔案內容
for (FileItem item : list) {
//如果上傳的內容是表單內容(也就是不帶檔案的內容)
if (item.isFormField()) {
//將表單中獲得的名稱獲取
String name = item.getFieldName();
//將內容獲取,內容為utf-8編碼方式
String value = item.getString("utf-8");
//將名稱和值放置到map中;
map.put(name, value);
} else {
//否則是帶有檔案的內容
String name = item.getName();
// 建立隨機名稱,這樣能夠將上傳的商品圖片名稱唯一
String uuidName = UUID.randomUUID().toString() + name;
// 建立檔案儲存的物理路徑
String path = this.getServletContext().getRealPath(
"/WEB-INF/upload");
//獲取檔案的hash值
int hashCode = uuidName.hashCode();
//將檔案的hash值轉換成十六進位制的字串
String hashStr = Integer.toHexString(hashCode);
// 講獲取的hashStr轉換成陣列
char hss[] = hashStr.toCharArray();
//初始化圖片上傳的目錄是upload資料夾下
String imgurl= "/WEB-INF/upload";
//為了讓圖片上傳的資料夾儲存的圖片均衡,遍歷
for (char c : hss) {
path += "/" + c;
imgurl += "/" + c;
}
imgurl += "/" + uuidName;
//將圖片url放在map中
map.put("imgurl", imgurl);
//建立資料夾
new File(path).mkdirs();
System.out.println(path);
// 檔案的讀寫
InputStream in = item.getInputStream();
OutputStream out = new FileOutputStream(new File(path,uuidName));
IOUtils.In2Out(in, out);
IOUtils.close(in, out);
// 刪除臨時檔案
item.delete();
PicUtils picUtils = new PicUtils(path+"/"+uuidName);
picUtils.resizeByHeight(100);
}
}
Prod prod = new Prod();
//將map中的值對映到商品中
BeanUtils.populate(prod, map);
service.addProd(prod);
//3 提示成功,返回首頁
response.getWriter().write("新增商品成功!3秒回首頁");
response.setHeader("Refresh", "3;url="+request.getContextPath()+"/index.jsp");
} catch (Exception e) {
e.printStackTrace();
}
Service相關操作:
public void addProd(Prod prod) {
dao.addProd(prod);
}
Dao相關操作:
//定義sql語句,插入商品名、商品價格、商品種類,商品庫存,商品圖片地址,商品描述
String sql = "insert into products values (null,?,?,?,?,?,?)";
QueryRunner runner = new QueryRunner(DaoUtils.getSource());
try {
runner.update(sql,prod.getName(),prod.getPrice(),prod.getCategory(),prod.getPnum(),prod.getImgurl(),prod.getDescription());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}