使用MVC三层架构实现对数据库表的增删改查操作(全部代码)

一.环境:

1.idea:2021
2.jdk:1.8
3.maven:apache-maven-3.6.1
4.tomcat:tomcat 8.5.4

二.项目结构


三.编写的思路

1.准备工作:

2.实现增删改查思路:



3:提供一个看懂的思路
(1)创建一个工程/模块(webapp);
(2)准备一个数据库db1,里面有一张表brand(上面图那样的);
(3)创建三层架构的包结构:mapper(dao)数据库
service
web
以及实体类包(pojo)和工具类包(util),并且将代码复制进去(下面有源代码)
(4)配置mybatis的环境(上面有张图)
(5)开始查询操作:页面上有一个超链接”查询所有”,点进去后在另一个界面的表单上显示查询到的表
怎么写呢?
思路如下:
1.在BrandMapper写查询方法,用注解的方式;
2.在BrandService里面实现这个方法;
3.在SelectAllServlet里面用service调用查询方法,转到查询后的界面(其中包括几个jsp页面数据的接收)
其他逻辑比它稍微复杂一点点,大差不差!
(6)需要注意的部分:
1.乱码的处理;
2.命名结构不一致;
3.除了查询,其他事务都需要提交;
(7)效果:(放在最后啦)
(8)看不懂的话:联系我!!!

四.代码

BrandMapper

package com.itheima.mapper;import com.itheima.pojo.Brand;import org.apache.ibatis.annotations.*;import java.util.List;public interface BrandMapper {/** * 查询所有 * @return */@Select("select * from tb_brand")@ResultMap("brandResultMap")//解决不同名问题List<Brand> selectAll();/** * 插入 * @param brand */@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")void add( Brand brand);/** * 根据id查 * @param id * @return */@Select("select * from tb_brand where id=#{id}")@ResultMap("brandResultMap")//解决不同名问题Brand selectById(int id);/** * 修改 * @param brand */@Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id = #{id}")void update(Brand brand);/** * 根据id删除 */@Delete("delete from tb_brand where id=#{id}")voiddeleteById(int id);}

**Brand **

package com.itheima.pojo;/** * 品牌实体类 */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;}@Overridepublic String toString() {return "Brand{" +"id=" + id +", brandName='" + brandName + '\'' +", companyName='" + companyName + '\'' +", ordered=" + ordered +", description='" + description + '\'' +", status=" + status +'}';}}

**BrandService **

package com.itheima.service;import com.itheima.mapper.BrandMapper;import com.itheima.pojo.Brand;import com.itheima.util.SqlSessionFactoryUtils;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import java.util.List;public class BrandService {SqlSessionFactory factory= SqlSessionFactoryUtils.getSqlSessionFactory();/** * 查询所有 * @return */public List<Brand> selectAll(){//调用BrandMapper的selectAll()//2.获取 sqlSession对象SqlSession sqlSession=factory.openSession();//3.获取BrandMapperBrandMapper mapper = sqlSession.getMapper(BrandMapper.class);//4.调用方法List<Brand> brands = mapper.selectAll();sqlSession.close();return brands;}/** * 新增 * @param brand */public void add(Brand brand){SqlSession sqlSession = factory.openSession();BrandMapper mapper=sqlSession.getMapper(BrandMapper.class);mapper.add(brand);sqlSession.commit();sqlSession.close();}/** * 根据id查 * @param id * @return */public Brand selectById(int id){SqlSession sqlSession = factory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);Brand brand = mapper.selectById(id);sqlSession.close();return brand;}/** * 修改 * @param brand */public void update(Brand brand){SqlSession sqlSession = factory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);mapper.update(brand);sqlSession.commit();sqlSession.close();}public void deleteById(int id){SqlSession sqlSession = factory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);mapper.deleteById(id);sqlSession.commit();sqlSession.close();}}

**SqlSessionFactoryUtils **

package com.itheima.util;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;import java.io.InputStream;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;}}

**AddServlet **

package com.itheima.web;import com.itheima.pojo.Brand;import com.itheima.service.BrandService;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;import java.util.List;@WebServlet("/addServlet")public class AddServlet extends HttpServlet {private BrandService service=new BrandService();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//处理post请求乱码问题request.setCharacterEncoding("utf-8");//1.接收表单提交的数据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.转发到查询所有的servletrequest.getRequestDispatcher("/selectAllServlet").forward(request,response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}}

**DeleteByIdServlet **

package com.itheima.web;import com.itheima.pojo.Brand;import com.itheima.service.BrandService;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.util.List;@WebServlet("/deleteByIdServlet")public class DeleteByIdServlet extends HttpServlet {private BrandService service=new BrandService();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.接收数据idString id = request.getParameter("id");//2.调用service方法service.deleteById(Integer.parseInt(id));List<Brand> brands = service.selectAll();request.setAttribute("brands",brands);request.getRequestDispatcher("/brand.jsp").forward(request,response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}}

**SelectAllServlet **

package com.itheima.web;import com.itheima.pojo.Brand;import com.itheima.service.BrandService;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;import java.util.List;@WebServlet("/selectAllServlet")public class SelectAllServlet extends HttpServlet {BrandService service = new BrandService();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.调用BrandService完成查询List<Brand> brands = service.selectAll();//2.存入request中request.setAttribute("brands",brands);//3.转发到brands.jsprequest.getRequestDispatcher("/brand.jsp").forward(request,response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}}

**SelectByIdServlet **

package com.itheima.web;import com.itheima.pojo.Brand;import com.itheima.service.BrandService;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet("/selectByIdServlet")public class SelectByIdServlet extends HttpServlet {private BrandService service=new BrandService();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.接收数据idString id = request.getParameter("id");//2.调用service方法查询Brand brand = service.selectById(Integer.parseInt(id));//3.存到request域里request.setAttribute("brand",brand);//转发到一个表单update,jsprequest.getRequestDispatcher("/brand.jsp").forward(request,response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}}

**UpdateServlet **

package com.itheima.web;import com.itheima.pojo.Brand;import com.itheima.service.BrandService;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;@WebServlet("/updateServlet")public class UpdateServlet extends HttpServlet {private BrandService service=new BrandService();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//处理post请求乱码问题request.setCharacterEncoding("utf-8");//1.接收表单提交的数据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.转发到查询所有的servlet request.getRequestDispatcher("/selectAllServlet").forward(request,response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}}

BrandMapper.xml

<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.itheima.mapper.BrandMapper"><resultMap id="brandResultMap" type="brand"><result column="brand_name" property="brandName"></result><result column="company_name" property="companyName"></result></resultMap></mapper>

mybatis-config.xml

<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><typeAliases><package name="com.itheima.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:///db1?useSSL=false&useServerPrepStmts=true"/><property name="username" value="root"/><property name="password" value="1234"/></dataSource></environment></environments><mappers><package name="com.itheima.mapper"/></mappers></configuration>

addBrand.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>添加品牌</title></head><body><h3>添加品牌</h3><form action="/brand-demo1/addServlet" method="post">品牌名称:<input name="brandName"><br>企业名称:<input name="companyName"><br>排序:<input name="ordered"><br>描述信息:<textarea rows="5" cols="20" name="description"></textarea><br>状态:<input type="radio" name="status" value="0">禁用<input type="radio" name="status" value="1">启用<br><input type="submit" value="提交"></form></body></html>

brand.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><input type="button" value="新增" id="add"><br><hr><table border="1" cellspacing="0" width="80%"><tr><th>序号</th><th>品牌名称</th><th>企业名称</th><th>排序</th><th>品牌介绍</th><th>状态</th><th>操作</th></tr><c:forEach items="${brands}" var="brand" varStatus="status"><tr align="center"><%--<td>${brand.id}</td>--%><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="/brand-demo1/selectByIdServlet?id=${brand.id}">修改</a> <a href="/brand-demo1/deleteByIdServlet?id=${brand.id}">删除</a></td></tr></c:forEach></table><script>document.getElementById("add").onclick=function (){location.href="/brand-demo1/addBrand.jsp";}</script></body></html>

update.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>修改品牌</title></head><body><h3>修改品牌</h3><form action="/brand-demo1/updateServlet" method="post"><%--隐藏域,提交id--%><input type="hidden" name="id" value="${brand.id}">品牌名称:<input name="brandName" value="${brand.brandName}"><br>企业名称:<input name="companyName" value="${brand.companyName}"><br>排序:<input name="ordered" value="${brand.ordered}"><br>描述信息:<textarea rows="5" cols="20" name="description">${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><input type="submit" value="提交"></form></body></html>

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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>brand-demo1</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>brand-demo1 Maven Webapp</name><url>http://www.example.com</url><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.34</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.2</version><scope>provided</scope></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version></plugin></plugins></build></project>

效果:


点击查询所有–>

点击修改—–>

修改后提交—–>

点击左上角新增按钮—–>

点击提交——>

点击删除——->