标签:
一、流程分析
1.图书管理模块介绍
2.
3.
4.添加图书第一步
5.添加图书第二步
二、代码
1.view层
(1)body.jsp
1 <body> 2 <h1 align="center">图书管理</h1> 3 <p align="center"> 4 <a href="<c:url value=‘/admin/AdminBookServlet?method=addPre‘/>" style="margin: 20px; font-size: 20px;">添加图书</a> 5 <a href="<c:url value=‘/adminjsps/admin/book/gj.jsp‘/>" style="margin: 20px; font-size: 20px;">高级搜索</a> 6 </p> 7 </body>
(2)add.jsp
1 <link rel="stylesheet" type="text/css" href="<c:url value=‘/adminjsps/admin/css/book/add.css‘/>"> 2 <link rel="stylesheet" type="text/css" href="<c:url value=‘/jquery/jquery.datepick.css‘/>"> 3 <script type="text/javascript" src="<c:url value=‘/jquery/jquery-1.5.1.js‘/>"></script> 4 <script type="text/javascript" src="<c:url value=‘/jquery/jquery.datepick.js‘/>"></script> 5 <script type="text/javascript" src="<c:url value=‘/jquery/jquery.datepick-zh-CN.js‘/>"></script> 6 <script type="text/javascript"> 7 $(function () { 8 $("#publishtime").datepick({dateFormat:"yy-mm-dd"}); 9 $("#printtime").datepick({dateFormat:"yy-mm-dd"}); 10 11 $("#btn").addClass("btn1"); 12 $("#btn").hover( 13 function() { 14 $("#btn").removeClass("btn1"); 15 $("#btn").addClass("btn2"); 16 }, 17 function() { 18 $("#btn").removeClass("btn2"); 19 $("#btn").addClass("btn1"); 20 } 21 ); 22 23 $("#btn").click(function() { 24 var bname = $("#bname").val(); 25 var currPrice = $("#currPrice").val(); 26 var price = $("#price").val(); 27 var discount = $("#discount").val(); 28 var author = $("#author").val(); 29 var press = $("#press").val(); 30 var pid = $("#pid").val(); 31 var cid = $("#cid").val(); 32 var image_w = $("#image_w").val(); 33 var image_b = $("#image_b").val(); 34 35 if(!bname || !currPrice || !price || !discount || !author || !press || !pid || !cid || !image_w || !image_b) { 36 alert("图名、当前价、定价、折扣、作者、出版社、1级分类、2级分类、大图、小图都不能为空!"); 37 return false; 38 } 39 40 if(isNaN(currPrice) || isNaN(price) || isNaN(discount)) { 41 alert("当前价、定价、折扣必须是合法小数!"); 42 return false; 43 } 44 $("#form").submit(); 45 }); 46 }); 47 48 function loadChildren() { 49 var pid = $("#pid").val(); 50 $.getJSON("/goods/admin/AdminBookServlet", 51 { 52 method: "ajaxFindChildren", 53 pid: pid, 54 }, 55 function(data, textStatus, jqXHR) { 56 $("#cid").empty(); 57 $("#cid").append("<option>====请选择2级分类====</option>"); 58 var option; 59 $.each(data, function(i,item){ 60 option = $("<option>").val(item.cid).text(item.cname); 61 $("#cid").append(option); 62 }); 63 }); 64 } 65 66 67 </script> 68 </head> 69 70 <body> 71 <div> 72 <p style="font-weight: 900; color: red;">${msg }</p> 73 <form action="<c:url value=‘/admin/AdminAddBookServlet‘/>" enctype="multipart/form-data" method="post" id="form"> 74 <div> 75 <ul> 76 <li>书名: <input id="bname" type="text" name="bname" value="Spring实战(第3版)(In Action系列中最畅销的Spring图书,近十万读者学习Spring的共同选择)" style="width:500px;"/></li> 77 <li>大图: <input id="image_w" type="file" name="image_w"/></li> 78 <li>小图: <input id="image_b" type="file" name="image_b"/></li> 79 <li>当前价:<input id="price" type="text" name="price" value="40.7" style="width:50px;"/></li> 80 <li>定价: <input id="currPrice" type="text" name="currPrice" value="59.0" style="width:50px;"/> 81 折扣:<input id="discount" type="text" name="discount" value="6.9" style="width:30px;"/>折</li> 82 </ul> 83 <hr style="margin-left: 50px; height: 1px; color: #dcdcdc"/> 84 <table> 85 <tr> 86 <td colspan="3"> 87 作者: <input type="text" id="author" name="author" value="Craig Walls" style="width:150px;"/> 88 </td> 89 </tr> 90 <tr> 91 <td colspan="3"> 92 出版社: <input type="text" name="press" id="press" value="人民邮电出版社" style="width:200px;"/> 93 </td> 94 </tr> 95 <tr> 96 <td colspan="3">出版时间:<input type="text" id="publishtime" name="publishtime" value="2013-6-1" style="width:100px;"/></td> 97 </tr> 98 <tr> 99 <td>版次: <input type="text" name="edition" id="edition" value="1" style="width:40px;"/></td> 100 <td>页数: <input type="text" name="pageNum" id="pageNum" value="374" style="width:50px;"/></td> 101 <td>字数: <input type="text" name="wordNum" id="wordNum" value="48700" style="width:80px;"/></td> 102 </tr> 103 <tr> 104 <td width="250">印刷时间:<input type="text" name="printtime" id="printtime" value="2013-6-1" style="width:100px;"/></td> 105 <td width="250">开本: <input type="text" name="booksize" id="booksize" value="16" style="width:30px;"/></td> 106 <td>纸张: <input type="text" name="paper" id="paper" value="胶版纸" style="width:80px;"/></td> 107 </tr> 108 <tr> 109 <td> 110 一级分类:<select name="pid" id="pid" onchange="loadChildren()"> 111 <option value="">==请选择1级分类==</option> 112 <c:forEach items="${parents }" var="parent"> 113 <option value="${parent.cid }">${parent.cname }</option> 114 </c:forEach> 115 </select> 116 </td> 117 <td> 118 二级分类:<select name="cid" id="cid"> 119 <option value="">==请选择2级分类==</option> 120 </select> 121 </td> 122 <td></td> 123 </tr> 124 <tr> 125 <td> 126 <input type="button" id="btn" class="btn" value="新书上架"> 127 </td> 128 <td></td> 129 <td></td> 130 </tr> 131 </table> 132 </div> 133 </form> 134 </div> 135 136 </body> 137 </html>
2.servlet层
(1)AdminBookServlet.java
1 /** 2 * 查询指定一级分类的所有二级分类 3 * @param req 4 * @param resp 5 * @return 6 * @throws ServletException 7 * @throws IOException 8 */ 9 public String ajaxFindChildren(HttpServletRequest req, HttpServletResponse resp) 10 throws ServletException, IOException { 11 String pid = req.getParameter("pid"); 12 List<Category> children = categoryService.findChildren(pid); 13 resp.getWriter().print(toJson(children)); 14 return null; 15 } 16 17 private String toJson(List<Category> categoryList) { 18 if(categoryList == null || categoryList.size() == 0) return null; 19 StringBuilder sb = new StringBuilder("["); 20 for(Category category : categoryList) { 21 sb.append(toJson(category)); 22 sb.append(","); 23 } 24 sb.deleteCharAt(sb.length()-1); 25 sb.append("]"); 26 return sb.toString(); 27 } 28 29 private String toJson(Category category) { 30 StringBuilder sb = new StringBuilder("{"); 31 sb.append("\"cid\":\"").append(category.getCid()).append("\","); 32 sb.append("\"cname\":\"").append(category.getCname()).append("\""); 33 sb.append("}"); 34 return sb.toString(); 35 } 36 37 /** 38 * 加载一级分类 39 * @param req 40 * @param resp 41 * @return 42 * @throws ServletException 43 * @throws IOException 44 */ 45 public String addPre(HttpServletRequest req, HttpServletResponse resp) 46 throws ServletException, IOException { 47 req.setAttribute("parents", categoryService.findParents()); 48 return "/adminjsps/admin/book/add.jsp"; 49 }
(1)AdminAddBookServlet.java
1 package com.tony.goods.admin.book.web.servlet; 2 3 import java.awt.Image; 4 import java.io.File; 5 import java.io.IOException; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 import javax.swing.ImageIcon; 15 16 import org.apache.commons.fileupload.FileItem; 17 import org.apache.commons.fileupload.FileItemFactory; 18 import org.apache.commons.fileupload.FileUploadException; 19 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 20 import org.apache.commons.fileupload.servlet.ServletFileUpload; 21 22 import cn.itcast.commons.CommonUtils; 23 24 import com.tony.goods.book.domain.Book; 25 import com.tony.goods.book.service.BookService; 26 import com.tony.goods.category.domain.Category; 27 import com.tony.goods.category.service.CategoryService; 28 29 public class AdminAddBookServlet extends HttpServlet { 30 31 public void doPost(HttpServletRequest request, HttpServletResponse response) 32 throws ServletException, IOException { 33 /* 34 * 1. commons-fileupload的上传三步 35 */ 36 // 创建工具 37 FileItemFactory factory = new DiskFileItemFactory(); 38 /* 39 * 2. 创建解析器对象 40 */ 41 ServletFileUpload sfu = new ServletFileUpload(factory); 42 sfu.setFileSizeMax(80 * 1024);//设置单个上传的文件上限为80KB 43 /* 44 * 3. 解析request得到List<FileItem> 45 */ 46 List<FileItem> fileItemList = null; 47 try { 48 fileItemList = sfu.parseRequest(request); 49 } catch (FileUploadException e) { 50 error("上传的文件超出了80KB", request, response); 51 return; 52 } 53 /* 54 * 4. 把List<FileItem>封装到Book对象中 55 * 4.1 首先把“普通表单字段”放到一个Map中,再把Map转换成Book和Category对象,再建立两者的关系 56 */ 57 Map<String,Object> map = new HashMap<String, Object>(); 58 for(FileItem fileItem : fileItemList) { 59 if(fileItem.isFormField()) {//如果是普通表单字段 60 map.put(fileItem.getFieldName(), fileItem.getString("UTF-8")); 61 } 62 } 63 Book book = CommonUtils.toBean(map, Book.class);//把Map中大部分数据封装到Book对象中 64 Category category = CommonUtils.toBean(map, Category.class);//把Map中cid封装到Category中 65 book.setCategory(category); 66 67 /* 68 * 4.2 把上传的图片保存起来 69 * > 获取文件名:截取之 70 * > 给文件添加前缀:使用uuid前缀,为也避免文件同名现象 71 * > 校验文件的扩展名:只能是jpg 72 * > 校验图片的尺寸 73 * > 指定图片的保存路径,这需要使用ServletContext#getRealPath() 74 * > 保存之 75 * > 把图片的路径设置给Book对象 76 */ 77 // 获取文件名 78 FileItem fileItem = fileItemList.get(1);//获取大图 79 String filename = fileItem.getName(); 80 // 截取文件名,因为部分浏览器上传的绝对路径 81 int index = filename.indexOf("\\"); 82 if(index != -1) { 83 filename = filename.substring(index + 1); 84 } 85 // 给文件名添加uuid前缀,避免文件同名现象 86 filename = CommonUtils.uuid() + "_" + filename; 87 // 校验文件名称的扩展名 88 if(!filename.toLowerCase().endsWith(".jpg")) { 89 error("上传的图片扩展名必须是JPG", request, response); 90 return; 91 } 92 // 校验图片的尺寸 93 // 保存上传的图片,把图片new成图片对象:Image、Icon、ImageIcon、BufferedImage、ImageIO 94 /* 95 * 保存图片: 96 * 1. 获取真实路径 97 */ 98 String savepath = this.getServletContext().getRealPath("/book_img"); 99 /* 100 * 2. 创建目标文件 101 */ 102 File destFile = new File(savepath, filename); 103 /* 104 * 3. 保存文件 105 */ 106 try { 107 fileItem.write(destFile); 108 } catch (Exception e) { 109 throw new RuntimeException(e); 110 } 111 // 校验尺寸 112 // 1. 使用文件路径创建ImageIcon 113 ImageIcon icon = new ImageIcon(destFile.getAbsolutePath()); 114 // 2. 通过ImageIcon得到Image对象 115 Image image = icon.getImage(); 116 // 3. 获取宽高来进行校验 117 if(image.getWidth(null) > 500 || image.getHeight(null) > 500) { 118 error("您上传的图片尺寸超出了500*500!", request, response); 119 destFile.delete(); 120 return; 121 } 122 123 // 把图片的路径设置给book对象 124 book.setImage_w("book_img/"+filename); 125 126 // 获取文件名 127 fileItem = fileItemList.get(2);//获取小图 128 filename = fileItem.getName(); 129 // 截取文件名,因为部分浏览器上传的绝对路径 130 index = filename.lastIndexOf("\\"); 131 if(index != -1) { 132 filename = filename.substring(index + 1); 133 } 134 filename = CommonUtils.uuid() + "_" + filename; 135 if(!filename.toLowerCase().endsWith(".jpg")) { 136 error("上传的图片扩展名必须是JPG", request, response); 137 return; 138 } 139 // 校验图片的尺寸 140 // 保存上传的图片,把图片new成图片对象:Image、Icon、ImageIcon、BufferedImage、ImageIO 141 /* 142 * 保存图片: 143 * 1. 获取真实路径 144 */ 145 savepath = this.getServletContext().getRealPath("/book_img"); 146 /* 147 * 2. 创建目标文件 148 */ 149 destFile = new File(savepath, filename); 150 /* 151 * 3. 保存文件 152 */ 153 try { 154 fileItem.write(destFile);//它会把临时文件重定向到指定的路径,再删除临时文件 155 } catch (Exception e) { 156 throw new RuntimeException(e); 157 } 158 // 校验尺寸 159 // 1. 使用文件路径创建ImageIcon 160 icon = new ImageIcon(destFile.getAbsolutePath()); 161 // 2. 通过ImageIcon得到Image对象 162 image = icon.getImage(); 163 // 3. 获取宽高来进行校验 164 if(image.getWidth(null) > 350 || image.getHeight(null) > 350) { 165 error("您上传的图片尺寸超出了350*350!", request, response); 166 destFile.delete();//删除图片 167 return; 168 } 169 170 // 把图片的路径设置给book对象 171 book.setImage_b("book_img/" + filename); 172 173 // 调用service完成保存 174 book.setBid(CommonUtils.uuid()); 175 BookService service = new BookService(); 176 service.add(book); 177 178 // 保存成功信息转发到msg.jsp 179 request.setAttribute("msg", "添加图书成功!"); 180 request.getRequestDispatcher("/adminjsps/msg.jsp").forward(request, response); 181 } 182 183 private void error(String msg, HttpServletRequest request, 184 HttpServletResponse response) throws ServletException, IOException { 185 request.setAttribute("msg", msg); 186 request.setAttribute("parents", new CategoryService().findParents()); 187 request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response); 188 } 189 190 }
3.service层
(1).java
4.dao层
(1)BookDao.java
1 /** 2 * 添加图书 3 * @param book 4 * @throws SQLException 5 */ 6 public void add(Book book) throws SQLException { 7 String sql = "insert into t_book(bid,bname,author,price,currPrice," + 8 "discount,press,publishtime,edition,pageNum,wordNum,printtime," + 9 "booksize,paper,cid,image_w,image_b)" + 10 " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; 11 Object[] params = {book.getBid(),book.getBname(),book.getAuthor(), 12 book.getPrice(),book.getCurrPrice(),book.getDiscount(), 13 book.getPress(),book.getPublishtime(),book.getEdition(), 14 book.getPageNum(),book.getWordNum(),book.getPrinttime(), 15 book.getBooksize(),book.getPaper(), book.getCategory().getCid(), 16 book.getImage_w(),book.getImage_b()}; 17 qr.update(sql, params); 18 }
标签:
原文地址:http://www.cnblogs.com/shamgod/p/5181874.html