网上图书商城项目学习笔记-026添加一级分类
一、流程分析
二、代码
1.view层
(1)add.jsp
1 <script type="text/javascript"> 2 function checkForm() { 3 if(!$("#cname").val()) { 4 alert("分类名不能为空!"); 5 return false; 6 } 7 if(!$("#desc").val()) { 8 alert("分类描述不能为空!"); 9 return false; 10 } 11 return true; 12 } 13 </script> 14 <style type="text/css"> 15 body {background: rgb(254,238,189);} 16 </style> 17 </head> 18 19 <body> 20 <h3>添加1级分类</h3> 21 <h1></h1> 22 <p style="font-weight: 900; color: red">${msg }</p> 23 <form action="<c:url value='/admin/AdminCategoryServlet'/>" method="post" onsubmit="return checkForm()"> 24 <input type="hidden" name="method" value="addParent"/> 25 分类名称:<input type="text" name="cname" id="cname"/><br/> 26 分类描述:<textarea rows="5" cols="50" name="desc" id="desc"></textarea><br/> 27 <input type="submit" value="添加一级分类"/> 28 <input type="button" value="返回" onclick="history.go(-1)"/> 29 </form> 30 </body> 31 </html>
2.servlet层
(1)AdminCategoryServlet.java
1 /** 2 * 添加父级 3 * @param req 4 * @param resp 5 * @return 6 * @throws ServletException 7 * @throws IOException 8 */ 9 public String addParent(HttpServletRequest req, HttpServletResponse resp) 10 throws ServletException, IOException { 11 Category parent = CommonUtils.toBean(req.getParameterMap(), Category.class); 12 parent.setCid(CommonUtils.uuid()); 13 service.add(parent); 14 return findAll(req, resp); 15 }
3.service层
(1)AdminCategoryService.java
1 /** 2 * 添加分类 3 * @param category 4 */ 5 public void add(Category category) { 6 try { 7 categoryDao.add(category); 8 } catch (SQLException e) { 9 throw new RuntimeException(e); 10 } 11 }
4.dao层
(1)AdminCategoryDao.java
1 /** 2 * 添加分类 3 * @param category 4 * @throws SQLException 5 */ 6 public void add(Category category) throws SQLException { 7 String pid = null; 8 if(category.getParent() != null) { 9 pid = category.getParent().getCid(); 10 } 11 String sql = "insert into t_category(cid, cname, pid, `desc`) values (?,?,?,?)"; 12 Object [] params = {category.getCid(), category.getCname(), pid, category.getDesc()}; 13 qr.update(sql, params); 14 }
You can do anything you set your mind to, man!