案例-基于MVC和三层架构实现商品表的增删改查

文章目录

      • 0. 项目介绍
      • 1. 环境准备
      • 2. 查看所有
        • 2.1 编写BrandMapper接口
        • 2.2 编写服务类,创建BrandService,用于调用该方法
        • 2.5 编写Servlet
        • 2.4 编写brand.jsp页面
        • 2.5 测试
      • 3.添加
        • 3.1 编写BrandMapper接口 添加方法
        • 3.2 编写服务
        • 3.3 改写Brand.jsp页面,添加新增按钮,并跳转到新的jsp页面(addBrand页面)
        • 3.4 编写Servlet
        • 3.5 测试

0. 项目介绍

其他项目-用户登录注册页面:https://blog.csdn.net/meini32/article/details/132305323

项目介绍
需求:完成品牌数据的增删改查操作
案例-基于MVC和三层架构实现商品表的增删改查_第1张图片

技术框架说明

三层架构是将我们的项目分成了三个层面,分别是 表现层 、 业务逻辑层 、 数据访问层。
整个流程是,浏览器发送请求,表现层的Servlet接收请求并调用业务逻辑层的方法进行业务逻辑处理,而业务逻辑层方法调用数据访问层方法进行数据的操作,依次返回到serlvet,然后servlet将数据交由 JSP 进行展示。

  • 数据访问层:Mybatis、mysql
  • 业务逻辑层:JAVA
  • 表现层:JSP、Servlet

案例-基于MVC和三层架构实现商品表的增删改查_第2张图片

实现步骤

1. 环境准备

环境准备

    1. 创建新的项目 brand_demo,引入坐标配置pom文件()
    1. 创建三层架构的包结构
    1. 数据库表 tb_brand
    1. 实体类 Brand
    1. MyBatis 基础环境配置

      • Mybatis-config.xml

      • BrandMapper.xml

      • BrandMapper接口

案例-基于MVC和三层架构实现商品表的增删改查_第3张图片
案例-基于MVC和三层架构实现商品表的增删改查_第4张图片
案例-基于MVC和三层架构实现商品表的增删改查_第5张图片
案例-基于MVC和三层架构实现商品表的增删改查_第6张图片
Mybatis-config.xml


DOCTYPE configuration
        PUBLIC "-//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="123456"/>
            dataSource>
        environment>
    environments>

    <mappers>
        
        <package name="com.itheima.mapper"/>
    mappers>
configuration>

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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>brand-demoartifactId>
    <version>1.0-SNAPSHOTversion>

    <packaging>warpackaging>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>


    <dependencies>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.5version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.34version>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
        dependency>

        

        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
            <scope>providedscope>
        dependency>

        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>1.1.2version>
        dependency>


    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <version>2.2version>
            plugin>
        plugins>
    build>


project>

工具类 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{
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

属性名称对应不上解决方法
案例-基于MVC和三层架构实现商品表的增删改查_第7张图片
在BrandMapper映射文件里,定义映射关系


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">




<mapper namespace="com.itheima.mapper.BrandMapper">


    <resultMap id="brandRseultMap" type="brand">
        <result column="brand_name" property="brandName">result>
        <result column="company_name" property="companyName">result>
    resultMap>

mapper>

在接口方法中指定该映射

public interface BrandMapper {

    //查看所有
    @ResultMap("brandResultMap")
    @Select("select * from tb_brand;")
    List<Brand> selectAll();
}

在这里插入图片描述

2. 查看所有

说明:当我们点击 index.html 页面中的 查询所有 这个超链接时,就能查询到上图右半部分的数据。
在这里插入图片描述

2.1 编写BrandMapper接口

public interface BrandMapper {

    //查看所有
    @Select("select * from tb_brand;")
    List<Brand> selectAll();
}

2.2 编写服务类,创建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 sqlSessionFactory =SqlSessionFactoryUtils.getSqlSessionFactory();

    //查所有
    public List<Brand> selectAll(){
        //调用BrandMapper中的selectAll方法

        //获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取Mapper
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //调用方法
        List<Brand> brands = brandMapper.selectAll();

        sqlSession.close();
        return brands;

    }
}

2.5 编写Servlet

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 {
    //创建这个服务
    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);
    }
}

2.4 编写brand.jsp页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Titletitle>
head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
  <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>${brand.id}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==0}">
        <td>禁止td>
      c:if>

      <td><a href="/brand-demo/selectByIdServlet?id=${brand.id}">修改a> <a href="#">删
        除a>td>

    tr>
  c:forEach>


table>

body>
html>

2.5 测试

案例-基于MVC和三层架构实现商品表的增删改查_第8张图片

3.添加

3.1 编写BrandMapper接口 添加方法

//添加
    @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

3.2 编写服务

public class BrandService {

    SqlSessionFactory sqlSessionFactory =SqlSessionFactoryUtils.getSqlSessionFactory();
    
    //添加数据

    public void add(Brand brand){
        //调用BrandMapper中的selectAll方法

        //获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取Mapper
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //调用方法
        brandMapper.add(brand);
        
        //提交事务
        sqlSession.commit();

        sqlSession.close();
        
    }
}

3.3 改写Brand.jsp页面,添加新增按钮,并跳转到新的jsp页面(addBrand页面)

案例-基于MVC和三层架构实现商品表的增删改查_第9张图片

<%--
  Created by IntelliJ IDEA.
  User: 11445
  Date: 2023/8/18
  Time: 20:31
  To change this template use File | Settings | File Templates.
--%>
<%@ 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="" 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>

案例-基于MVC和三层架构实现商品表的增删改查_第10张图片

3.4 编写Servlet

在 web 包下创建 AddServlet 的 servlet ,该 servlet 的逻辑如下:

  • 设置处理post请求乱码的字符集
  • 接收客户端提交的数据
  • 将接收到的数据封装到 Brand 对象中
  • 调用 BrandService 的 add() 方法进行添加的业务逻辑处理
  • 跳转到 selectAllServlet 资源重新查询数据
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("/addServlet")
public class AddServlet extends HttpServlet {

    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理post请求的乱码问题
        req.setCharacterEncoding("utf-8");


        //1. 接收表单提交的数据,封装为一个Brand对象
        String brandName = req.getParameter("brandName");
        String companyName = req.getParameter("companyName");
        String ordered = req.getParameter("ordered");
        String description = req.getParameter("description");
        String status = req.getParameter("status");

        //封装为一个Brand对象
        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
        req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

3.5 测试

案例-基于MVC和三层架构实现商品表的增删改查_第11张图片
案例-基于MVC和三层架构实现商品表的增删改查_第12张图片
案例-基于MVC和三层架构实现商品表的增删改查_第13张图片

你可能感兴趣的:(mvc,架构)