友佳书屋
1.功能演示
一、 类目
分析实体
类目,单词为 Category
实体的名称就定义下来了
|— 属性: categoryId(用于确定的唯一性); 类目名称 categoryName; 类目描述 categoryDescription
1.1 实体类:
1, 定义属性变量 2,使用快捷键Alt+Insert 生成getter和setter方法 3, 使用快捷键Alt+Insert 生成toString方法,便于打印查看具体数据 4,使用快捷键Alt+Insert 生成构造方法 4.1, 有参数的构造方法 4.2, 无参数的构造方法
public class Category { private int categoryId; private String categoryName; private String categoryDescription; // 有参数构造方法 要id public Category(int categoryId, String categoryName, String categoryDescription) { this.categoryId = categoryId; this.categoryName = categoryName; this.categoryDescription = categoryDescription; } // 有参数构造方法 不要id public Category(String categoryName, String categoryDescription) { this.categoryName = categoryName; this.categoryDescription = categoryDescription; } // 无参数的构造方法: Alt+Insert 再去选择 Override Methods 默认Object()方法 直接回车 public Category() { super(); } @Override public String toString() { return "Category{" + "categoryId=" + categoryId + ", categoryName='" + categoryName + '\'' + ", categoryDescription='" + categoryDescription + '\'' + '}'; } public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getCategoryDescription() { return categoryDescription; } public void setCategoryDescription(String categoryDescription) { this.categoryDescription = categoryDescription; } }
1.2 编写Service层
Service层有 接口和实现类
(1)先去编写接口,接口的命名规范为 [实体类的名称+ Service],本接口为CategoryService,实现类为CategoryServiceImpl
(2)考虑该接口内哪些功能,功能对应的是方法。
功能如下:
增加类目
删除类目
修改类目
查询所有类目
根据类目编号categoryId查询类目
对应的是五个方法:
增加类目方法, 参数列表是:Category category; 返回值类型为int
删除类目方法, 参数列表是:int categoryId; 返回值类型为int
修改类目方法, 参数列表是:Category category; 返回值类型为int
查询所有类目方法, 无参数 返回值类型为List<Category>;
【因为查询的所有类目,不再是单一的一个类目,需要有容器存储所有类目对象,该容器合适的是集合,便于查询的是ArrayList集合。{ArrayList特性是 查询快、增删慢 | LinkedList特性是 查询慢、增删快}】
根据类目编号查询方法,参数列表是:int categoryId; 返回值类型为Category;
【因为查询的是一个类目,所有就是对象存储。】
代码如下:
package cn.javabs.service; import cn.javabs.entity.Category; import java.util.List; public interface CategoryService { int addCategory(Category category); int delCategory(int categoryId); int editCategory(Category category); List<Category> findAllCategory(); Category findCategoryById(int categoryId); }
接口的实现类:
无需代码编写,可利用idea软件进行代码生成,步骤如下:
(1) 放在接口名称后,按快捷键 Alt+Enter
选中 Implement Interface
回车,需要补充包名.impl
再去点击OK
继续选择OK
效果如图:
1.3 编写Dao层
Dao层有 接口和实现类
(1)先去编写接口,接口的命名规范为 [实体类的名称+ Dao],本接口为CategoryDao,实现类为CategoryDaoImpl
(2)考虑该接口内哪些功能,功能对应的是方法。
功能如下:
增加类目
删除类目
修改类目
查询所有类目
根据类目编号categoryId查询类目
对应的是五个方法:
增加类目方法, 参数列表是:Category category; 返回值类型为int
删除类目方法, 参数列表是:int categoryId; 返回值类型为int
修改类目方法, 参数列表是:Category category; 返回值类型为int
查询所有类目方法, 无参数 返回值类型为List<Category>;
【因为查询的所有类目,不再是单一的一个类目,需要有容器存储所有类目对象,该容器合适的是集合,便于查询的是ArrayList集合。{ArrayList特性是 查询快、增删慢 | LinkedList特性是 查询慢、增删快}】
根据类目编号查询方法,参数列表是:int categoryId; 返回值类型为Category;
【因为查询的是一个类目,所有就是对象存储。】
在CategoryServiceImpl实现类内编写实例化操作,步骤如下:
(1)在类内编写 实例化{也就是new}
CategoryDao categoryDao = new CategoryDaoImpl(); 对象名称是categoryDao
写完会发现,CategoryDao 、CategoryDaoImpl 呈后红色状态,暂不需要处理,可继续编写。
(2) 利用对象去完成增删改查操作
添加类目方法:return categoryDao.add(Category) ;
删除类目方法:return categoryDao.del(CategoryId) ;
修改类目方法:return categoryDao.edit(Category) ;
获取所有类目方法:return categoryDao.getAllCategory() ;
根据编号查询类目方法:return categoryDao.getCategoryById(CategoryId) ;
写完以上方法,仍会呈现红色的状态
(3)解决报错问题
①将光标放在CategoryDao后,按快捷键 Alt+Enter,选择 Create Interface CategoryDao
修改包名为dao,然后Ok回车
② 将光标放在add后,按快捷键 Alt+Enter,选择 Create method add in CategoryDao 然后回车
③ 将光标放在del后,按快捷键 Alt+Enter,选择 Create method del in CategoryDao 然后回车
④ 将光标放在edit后,按快捷键 Alt+Enter,选择 Create method edit in CategoryDao 然后回车
⑤ 将光标放在getAllCategory后,按快捷键 Alt+Enter,选择 Create method getAllCategory in CategoryDao 然后回车
⑥ 将光标放在getCategoryById后,按快捷键 Alt+Enter,选择 Create method getCategoryById in CategoryDao 然后回车
⑦ 将光标放在CategoryDaoImpl实现类后,按快捷键 Alt+Enter,选择 Create class CategoryDaoImpl
修改包名为dao.impl,然后OK
(4)回到CategoryDaoImpl实现类内,会发现报错:
解决办法: 将光标放在CategoryDao后,按快捷键 Alt+Enter,选择 implment methods 然后回车、再回车。
截至到目前,需进一步编写CategoryDaoImpl实现类内的功能代码,却发现缺少数据源连接池,接下来进行创建数据库连接池,这里采用的是阿里巴巴数据源Druid,具体内容点此查看。
1.4 创建工具类
下载jar包
package cn.javabs.util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class DruidUtil { public static DataSource dataSource; static { try { InputStream is = DruidUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pro = new Properties(); pro.load(is); dataSource = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { throw new RuntimeException(e); } } public static DataSource getDataSource(){ return dataSource; } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
在src下创建配置文件:jdbc.proeprties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/bookmarket username=root password=sorry
1.5 完善CategoryDaoImpl
package cn.javabs.dao.impl; import cn.javabs.dao.CategoryDao; import cn.javabs.entity.Category; import cn.javabs.util.DruidUtil; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.sql.SQLException; import java.util.List; public class CategoryDaoImpl implements CategoryDao { QueryRunner qr = new QueryRunner(DruidUtil.getDataSource()); @Override public int add(Category category) { try { return qr.update("insert into category(categoryName,categoryDescription) values(?,?)", category.getCategoryName(),category.getCategoryDescription()); } catch (SQLException e) { throw new RuntimeException(e);// 转成运行时异常抛出 } } @Override public int del(int categoryId) { try { return qr.update("delete from category where categoryId = ?",categoryId); } catch (SQLException e) { throw new RuntimeException(e);// 转成运行时异常抛出 } } @Override public int edit(Category category) { try { return qr.update("update category set categoryName = ?,categoryDescription = ? where categoryId = ?", category.getCategoryName(),category.getCategoryDescription(),category.getCategoryId()); } catch (SQLException e) { throw new RuntimeException(e);// 转成运行时异常抛出 } } @Override public List<Category> getAllCategory() { try { return qr.query("select * from category",new BeanListHandler<Category>(Category.class)); } catch (SQLException e) { throw new RuntimeException(e);// 转成运行时异常抛出 } } @Override public Category getCategoryById(int categoryId) { try { return qr.query("select * from category where categoryId = ?",new BeanHandler<Category>(Category.class),categoryId); } catch (SQLException e) { throw new RuntimeException(e);// 转成运行时异常抛出 } } }
1.6 编写 CategoryServlet
package cn.javabs.web.servlet; import cn.javabs.entity.Category; import cn.javabs.service.CategoryService; import cn.javabs.service.impl.CategoryServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.invoke.VolatileCallSite; import java.util.List; @WebServlet("/categoryServlet") public class CategoryServlet extends HttpServlet { CategoryService cs = new CategoryServiceImpl(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 解决乱码 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); // 接受参数、用于判断是找哪个方法 String op = request.getParameter("op"); switch (op){ case "addCategory": addCategory(request, response); break; case "delCategory": delCategory(request, response); break; case "editCategory": editCategory(request, response); break; case "categoryList": categoryList(request, response); break; case "updateCategory": updateCategory (request, response); break; default: System.out.println("没有找到对应的参数!请查证"); } } // 修改之数据回显 private void updateCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); String categoryName = request.getParameter("categoryName"); String categoryDescription = request.getParameter("categoryDescription"); int categoryId = Integer.parseInt(id); Category category = new Category(categoryId, categoryName, categoryDescription); int row = cs.editCategory(category); if (row>0){ request.setAttribute("msg","修改类目成功!"); request.getRequestDispatcher("message.jsp").forward(request,response); }else{ request.setAttribute("msg","修改类目失败!"); request.getRequestDispatcher("message.jsp").forward(request,response); } } private void categoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Category> list = cs.findAllCategory(); if (list.size() > 0&& list != null) { request.setAttribute("list", list); request.getRequestDispatcher("categoryList.jsp").forward(request,response); }else{ request.setAttribute("msg","尚未查询到相关类目!"); request.getRequestDispatcher("message.jsp").forward(request,response); } } // 数据回显 private void editCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); int categoryId = Integer.parseInt(id); Category category = cs.findCategoryById(categoryId); if (category != null){ request.setAttribute("category", category); request.getRequestDispatcher("editCategory.jsp").forward(request,response); }else{ request.setAttribute("msg","修改类目失败,请查证!"); request.getRequestDispatcher("message.jsp").forward(request,response); } } private void delCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); int categoryId = Integer.parseInt(id); int row = cs.delCategory(categoryId); if (row>0){ request.setAttribute("msg","删除类目成功!"); request.getRequestDispatcher("message.jsp").forward(request,response); }else{ request.setAttribute("msg","删除类目失败!"); request.getRequestDispatcher("message.jsp").forward(request,response); } } /** * 添加类目 * @param request * @param response */ private void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String categoryName = request.getParameter("categoryName"); String categoryDescription = request.getParameter("categoryDescription"); Category category = new Category(categoryName, categoryDescription); int row = cs.addCategory(category); if (row>0){ request.setAttribute("msg","添加类目成功!"); request.getRequestDispatcher("message.jsp").forward(request,response); }else{ request.setAttribute("msg","添加类目失败!"); request.getRequestDispatcher("message.jsp").forward(request,response); } } }
1.7页面布局级设计
1.7.1添加页面
<%-- Created by IntelliJ IDEA. User: Mryang Date: 2021/10/11 Time: 14:18 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加图书类目</title> </head> <body> <form action="/categoryServlet?op=addCategory" method="post"> 类目名称:<input type="text" name="categoryName" id="categoryName"> <br/> 类目描述:<input type="text" name="categoryDescription" id="categoryDescription"> <br/> <input type="submit" value="添加类目"> </form> </body> </html>
1.7.2查询页面
<%-- Created by IntelliJ IDEA. User: Mryang Date: 2021/10/11 Time: 14:22 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!--不要遗忘这条指令--> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <table> <tr> <td>编号</td> <td>名称</td> <td>描述</td> <td>操作</td> </tr> <c:forEach items="${list}" var="item"> <tr> <td>${item.categoryId}</td> <td>${item.categoryName}</td> <td>${item.categoryDescription}</td> <td> <a href="/categoryServlet?op=editCategory&id=${item.categoryId}">修改</a> <a href="JavaScript:deleteCategory('${item.categoryId}')">删除</a> </td> </tr> </c:forEach> </table> </body> </html> <script> function deleteCategory(id) { var sure = confirm("您确定要删除此项吗?") if (sure){ location.href = "/categoryServlet?op=delCategory&id=" + id; } } </script>
1.7.3修改页面
<%-- Created by IntelliJ IDEA. User: Mryang Date: 2021/10/11 Time: 14:18 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>修改图书类目</title> </head> <body> <form action="/categoryServlet?op=updateCategory&id=${category.categoryId}" method="post"> 类目名称:<input type="text" value="${category.categoryName}" name="categoryName" id="categoryName"> <br/> 类目描述:<input type="text" value="${category.categoryDescription}" name="categoryDescription" id="categoryDescription"> <br/> <input type="submit" value="修改类目"> </form> </body> </html>
1.8 编写MySQL数据库的代码
-- 创建数据库 create database bookmarket; -- 选中数据库 use bookmarket; -- 创建 类目 数据表 CREATE table category( categoryId int primary key auto_increment, -- auto_increment 自动递增 categoryName varchar(50), categoryDescription varchar(250) );