项目简介
1.四层架构的模型图
2.步骤
1.创建数据库(创建表) 2.导入需要的jar包(导入WebContent目录下的WEB-INF下的bin目录里面) 3.创建包: com.yfh.pojo(装实体类) com.yfh.web(装dao类 com.yfh.service(装service类 com.yfh.servlet(装servlet类) com.yfh.util(装工具类) 4.创建JDBC工具类(使用Druid数据库连接池 5.配置数据库及连接池参数(放于src下) 6.实体类层:用来封装属性及其get set方法 toString方法,有参构造方法,无参构造方法等。 7.Dao层:对数据库的增删改查方法的封装(操作数据库)也是属于业务逻辑 8.Servlet(Controller):流程控制 9.Service:处理业务逻辑 10.jsp(View)页面(位于WebContent目录下)
项目实现
项目包预览
环境搭建
创建新的模块 brand_demo,并在 pom.xml 文件引入坐标
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>brand-demo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>brand-demo Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <finalName>brand-demo</finalName> </build> </project>
在 com.yfh 包下创建三层架构的包结构,并将创建(若现成的则导入)数据库表 tb_brand
在 com.yfh.pojo 包下创建实体类 Brand
/** * 品牌实体类 */ public class Brand { // id 主键 private Integer id; // 品牌名称 private String brandName; // 企业名称 private String companyName; // 排序字段 private Integer ordered; // 描述信息 private String description; // 状态:0:禁用 1:启用 private Integer status; public Brand() { } public Brand(Integer id, String brandName, String companyName, String description) { this.id = id; this.brandName = brandName; this.companyName = companyName; this.description = description; } public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) { this.id = id; this.brandName = brandName; this.companyName = companyName; this.ordered = ordered; this.description = description; this.status = status; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public Integer getOrdered() { return ordered; } public void setOrdered(Integer ordered) { this.ordered = ordered; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() { return "Brand{" + "id=" + id + ", brandName='" + brandName + '\'' + ", companyName='" + companyName + '\'' + ", ordered=" + ordered + ", description='" + description + '\'' + ", status=" + status + '}'; } }
准备 MyBatis 基础环境
在 com.yfh.mapper 创建 BrandMapper
public interface BrandMapper { }
在 resources 文件夹下添加 Mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.yfh.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///test?useSSL=false&useServerPrepStmts=true"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <package name="com.yfh.mapper"/> </mappers> </configuration>
在 resources 文件夹下创建 com.yfh.mapper 包,并在该包下创建 BrandMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.yfh.mapper.BrandMapper"> <resultMap id="brandResultMap" type="brand"> <result column="brand_name" property="brandName"></result> <result column="company_name" property="companyName"></result> </resultMap> </mapper>
查询所有功能实现
实现 Dao 层,通过 select * from tb_brand 实现查询表中的所有内容
public interface BrandMapper { /** * 查询所有 * @return */ @Select("select * from tb_brand") @ResultMap("brandResultMap") List<Brand> selectAll(); }
在实现 Service 层之前将 SqlSessionFactory 类导入到 com.yfh.util 包下
public class SqlSessionFactoryUtils { private static SqlSessionFactory sqlSessionFactory; static { //静态代码块会随着类的加载而自动执行,且只执行一次 try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory(){ return sqlSessionFactory; } }
实现 Service 层,创建 BrandService 类,实现查询所有的逻辑功能 (基本步骤:建立sql会话,通过sql会话获取mapper对象,最后调用存储在一个变量后返回,注意查询完之后一定要关闭会话)
/** * 查询所有 * @return */ public List<Brand> selectAll(){ //调用BrandMapper.selectAll() SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); //1.获取SqlSession SqlSession sqlSession = factory.openSession(); //2.获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //3.调用方法 List<Brand> brands = mapper.selectAll(); sqlSession.close(); return brands; }
实现 web 层之写好 index.html 页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/brand-demo/selectAllServlet">查询所有</a> </body> </html>
实现 web 层之实现 SelectAllServlet 类实现页面交互
@WebServlet("/selectAllServlet") public class SelectAllServlet extends HttpServlet { private BrandService service = new BrandService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 调用BrandService完成查询 List<Brand> brands = service.selectAll(); //2.存入request域中 request.setAttribute("brands",brands); //3.转发到brand.jsp request.getRequestDispatcher("/brand.jsp").forward(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }
实现 web 层之在 webapp 包下实现 brand.jsp 页面
<%-- Created by IntelliJ IDEA. User: yy Date: 2023/1/10 Time: 00:41 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <a href="addBrand.jsp"> <button>新增</button> </a> <hr> <table border="1" cellpadding="0" width="100%" align="center"> <tr align="center"> <td>序号</td> <td>品牌名称</td> <td>企业名称</td> <td>排序</td> <td>品牌介绍</td> <td>状态</td> <td>操作</td> </tr> <c:forEach items="${brands}" var="brand" varStatus="status"> <tr align="center"> <td>${status.count}</td> <td>${brand.brandName}</td> <td>${brand.companyName}</td> <td>${brand.ordered}</td> <td>${brand.description}</td> <c:if test="${brand.status == 1}"> <td>启用</td> </c:if> <c:if test="${brand.status != 1}"> <td>禁用</td> </c:if> <td><a href="/selectByIdServlet?id=${brand.id}">编辑</a> <a href="/deleteByIdServlet?id=${brand.id}">删除</a></td> </tr> </c:forEach> </table> </body> </html>
查询所有页面效果
添加数据功能实现
实现 Dao 层,通过 insert into tb_brand values(null,brand_name,company_name,ordered,description,status) 实现添加数据
public interface BrandMapper { /** * 添加数据 * @param brand */ @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})") void add(Brand brand); }
实现 Service 层,在 BrandService 类,实现查询所有的逻辑功能 (基本步骤:建立sql会话,通过sql会话获取mapper对象,最后调用并commit,注意查询完之后一定要关闭会话)
/** * 添加数据 * @param brand */ public void add(Brand brand){ //调用BrandMapper.selectAll() SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); //1.获取SqlSession SqlSession sqlSession = factory.openSession(); //2.获取brandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //3.调用方法 mapper.add(brand); sqlSession.commit(); sqlSession.close(); }
实现 web 层之在 brand.jsp 的头部添加添加 “按钮”
<input type="button" value="新增" id="add"><br>
实现 web 层之在 brand.jsp 的下面实现添加按钮的 js 脚本
<script> document.getElementById("add").onclick = function (){ location.href = "/brand-demo/addBrand.jsp"; } </script>
实现 web 层之写好 addBrand.jsp 页面
<%-- Created by IntelliJ IDEA. User: yy Date: 2023/1/10 Time: 13:52 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加品牌</title> </head> <body> <h3>添加品牌</h3> <form action="/addServlet" method="post"> 品牌名称:<input type="text" name="brandName"> <br> 企业名称:<input type="text" name="companyName"> <br> 排序:<input type="number" name="ordered"> <br> 描述信息:<textarea name="description" rows="1" cols="20"></textarea> <br> 状态: <input type="radio" name="status" value="0"> 禁用 <input type="radio" name="status" value="1"> 启用 <br> <button type="submit">提交</button> </form> </body> </html>
实现 web 层之实现 AddServlet 类实现页面交互
@WebServlet("/addServlet") public class AddServlet extends HttpServlet { private BrandService service = new BrandService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理POST请求的编码处理问题 request.setCharacterEncoding("utf-8"); //1.接收表单提交的数据,封装为一个Brand对象 String brandName = request.getParameter("brandName"); String companyName = request.getParameter("companyName"); String ordered = request.getParameter("ordered"); String description = request.getParameter("description"); String status = request.getParameter("status"); Brand brand = new Brand(); brand.setBrandName(brandName); brand.setCompanyName(companyName); brand.setOrdered(Integer.parseInt(ordered)); brand.setDescription(description); brand.setStatus(Integer.parseInt(status)); //2.调用Service,完成添加 service.add(brand); //3.转发到查询所有Servlet request.getRequestDispatcher("selectAllServlet").forward(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }
添加数据页面效果
修改数据功能实现
回显数据
实现 Dao 层,通过 select * from tb_brand where id=#{id} 实现添加数据
public interface BrandMapper { /** * 根据id查询 * @param id * @return */ @Select("select * from tb_brand where id=#{id}") @ResultMap("brandResultMap") Brand selectById(int id); }
实现 Service 层,创建 BrandService 类,实现根据id查询逻辑功能 (基本步骤:建立sql会话,通过sql会话获取mapper对象,最后调用存储在一个变量后返回,注意查询完之后一定要关闭会话);
/** * 根据id查询 * @param id * @return */ public Brand selectById(int id){ //调用BrandMapper.selectById(id) SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); //1.获取SqlSession SqlSession sqlSession = factory.openSession(); //2.获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //3.调用方法 Brand brand = mapper.selectById(id); sqlSession.close(); return brand; }
修改数据
实现 Dao 层,通过 update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id} 实现修改数据
@Update("update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id}") @ResultMap("brandResultMap") void update(Brand brand);
实现 Service 层,创建 BrandService 类,调用修改数据功能 (基本步骤:建立sql会话,通过sql会话获取mapper对象,注意查询完之后一定要关闭会话);
/** * 修改数据 * @param brand */ public void update(Brand brand){ //调用BrandMapper.update(brand) SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); //1. 获取SqlSession SqlSession sqlSession = factory.openSession(); //2.获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //3.调用方法 mapper.update(brand); sqlSession.commit(); sqlSession.close(); }
实现 web 层之在 brand.jsp 页面把修改链接添加链接地址
实现 web 层之在 brand.jsp 页面把修改链接添加链接地址
实现 web 层之在 updata.jsp 页面回显数据,注意回显的数据回传回id,需要把id隐藏起来,这是不需要展现给用户来看的;
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: yy Date: 2023/1/10 Time: 15:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>编辑</title> </head> <body> <h3>编辑品牌</h3> <form action="/upDateServlet" method="post"> <input type="text" name="id" value="${brand.id}"> 品牌名称:<input type="text" name="brandName" value="${brand.brandName}"> <br> 企业名称:<input type="text" name="companyName" value="${brand.companyName}"> <br> 排序:<input type="text" name="ordered" value="${brand.ordered}"> <br> 描述信息:<textarea name="description" rows="1" cols="20">${brand.description}</textarea> <br> 状态: <c:if test="${brand.status == 0}"> <input type="radio" name="status" value="0" checked> 禁用 <input type="radio" name="status" value="1"> 启用 <br> </c:if> <c:if test="${brand.status == 1}"> <input type="radio" name="status" value="0"> 禁用 <input type="radio" name="status" value="1" checked> 启用 <br> </c:if> <button type="submit">提交</button> </form> </body> </html>
实现 web 层之实现 UpdateServlet 类实现页面交互
@WebServlet("/updateServlet") public class UpdateServlet extends HttpServlet { private BrandService service = new BrandService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理POST请求的编码处理问题 request.setCharacterEncoding("utf-8"); //1.接收表单提交的数据,封装为一个Brand对象 String id = request.getParameter("id"); String brandName = request.getParameter("brandName"); String companyName = request.getParameter("companyName"); String ordered = request.getParameter("ordered"); String description = request.getParameter("description"); String status = request.getParameter("status"); Brand brand = new Brand(); brand.setId(Integer.parseInt(id)); brand.setBrandName(brandName); brand.setCompanyName(companyName); brand.setOrdered(Integer.parseInt(ordered)); brand.setDescription(description); brand.setStatus(Integer.parseInt(status)); //2.调用Service,完成修改 service.update(brand); //3.转发到SelectAllServlet request.getRequestDispatcher("selectAllServlet").forward(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }
删除数据(额外添加的功能)
实现 Dao 层,通过 delete from tb_brand where id=#{id} 实现删除数据
/** * 根据id删除数据 * @param id */ @Delete("delete from tb_brand where id=#{id}") @ResultMap("brandResultMap") void deleteById(int id);
实现 Service 层,创建 BrandService 类,调用删除数据功能 (基本步骤:建立sql会话,通过sql会话获取mapper对象,注意查询完之后一定要关闭会话);
/** * 根据id删除数据 * @param id */ public void delete(int id){ //调用BrandMapper.delete(id) SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); //1.获取SqlSession SqlSession sqlSession = factory.openSession(); //2.获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //3.调用方法 mapper.deleteById(id); sqlSession.commit(); sqlSession.close(); }
实现 web 层之在 brand.jsp 页面把删除链接添加链接地址
<a href="/brand-demo/deleteByIdServlet?id=${brand.id}">删除</a>
实现 web 层之实现 DeleteByIdServlet 类实现页面交互
@WebServlet("/deleteByIdServlet") public class DeleteByIdServlet extends HttpServlet { private BrandService service = new BrandService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.接收需要删除数据的id String id = request.getParameter("id"); //2.调用Service service.delete(Integer.parseInt(id)); //3.转发至SelectAllServlet request.getRequestDispatcher("selectAllServlet").forward(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }