JavaWeb06-MVC和三层架构

目录

一、MVC模式

1.概述

2.好处

二、三层架构

1.概述

三、MVC与三层架构

四、练习


一、MVC模式

1.概述

MVC是一种分层开发的模式,其中

M:Model,业务模型,处理业务 V: View,视图,界面展示 C:Controller,控制器,处理请求,调用型和视图

2.好处

  • 职责单一,互不影响

  • 有利于分工协作

  • 有利于组件重用

二、三层架构

1.概述

View视图不只是JSP!

数据访问层(持久层):对数据库的CRUD基本操作

一般命名为反转公司网址/controller

业务逻辑层(业务层):对业务逻辑进行封装,组合数据访问层层中基本功能,形成复杂的业务逻辑功能。

一般命名为反转公司网址/service

表现层:接收请求,封装数据,调用业务逻辑层,响应数据

一般命名为反转公司网址/dao或者mapper

三、MVC与三层架构

四、练习

给上次的数据添加一个状态字段,0禁用,1启用,2预售,设个默认值1即可

使用三层架构思想开发

参考下图:

java目录结构

代码,只写主要的了

service包下

java 复制代码
public class ProductService {
    final SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public List<Product> selectAll(){
        final SqlSession sqlSession = sqlSessionFactory.openSession();
        final ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
        final List<Product> products = mapper.selectAll();
        sqlSession.close();
        return products;
    };
}

web包下

java 复制代码
@WebServlet("/selectAll")
public class selectAll extends HttpServlet {
    private final ProductService productService = new ProductService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
​
        final List<Product> products = productService.selectAll();
        request.setAttribute("product",products);
        request.getRequestDispatcher("/jsp/product.jsp").forward(request,response);
    }
​
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

之后回到视图层

jsp:

java 复制代码
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: LEGION
  Date: 2024/3/13
  Time: 13:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%--<% final Object product = request.getAttribute("product");%>--%>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>product列表</h1>
    <table border="1px solid black">
        <tr>
            <th>商品序号</th>
            <th>商品id</th>
            <th>商品名</th>
            <th>商品图片</th>
            <th>商品价格</th>
            <th>商品评论数</th>
            <th>商品分类</th>
            <th>商品状态</th>
            <th>商品发布时间</th>
            <th>商品更新时间</th>
        </tr>
        <c:forEach items="${product}" var="product" varStatus="status">
            <tr>
                    <%--                index从0开始,count从1开始--%>
                <td>${status.count}</td>
                    <%--                ${user.id} => Id => getId()--%>
                <td>${product.id}</td>
                <td>${product.title}</td>
                <td><img src="${product.imgUrl}" alt="" width="75px" height="75px"></td>
                <td>${product.price}</td>
                <td>${product.comment}</td>
                <td>${product.category}</td>
                <td>${product.status}</td>
                <td>${product.gmtCreate}</td>
                <td>${product.gmtModified}</td>
            </tr>
        </c:forEach>
​
        </table>
​
    </body>
</html>

预览图:

添加:

html

html 复制代码
<form action="/product_demo_war/add" method="post">
      <input type="text" name="title" placeholder="商品名称"><br>
      <input type="text" name="price" placeholder="商品价格"><br>
<!--        图片上传在这里就先不写了-->
        <input type="number" name="category" placeholder="商品类型(数字就好)"><br>
        <input type="radio" name="status">启用
        <input type="radio" name="status">禁用
        <br>
        <input type="submit" value="添加">
    </form>

service:

java 复制代码
/**
 * 添加商品
 * @param product 商品对象
 */
public void add(Product product){
    final SqlSession sqlSession = sqlSessionFactory.openSession();
    final ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
    mapper.add(product);
    sqlSession.commit();
    sqlSession.close();
}

web:

java 复制代码
@WebServlet("/add")
public class Add extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductService productService = new ProductService();
        final String title = request.getParameter("title");
        final String price = request.getParameter("price");
        final Integer status = Integer.parseInt(request.getParameter("status"));
        final Integer category = Integer.parseInt(request.getParameter("category"));
        Product product = new Product(title,price,category,status);
        productService.add(product);
        request.getRequestDispatcher("/selectAll").forward(request,response);
    }
​
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

预览:

修改:

有两步:

  • 显示原先的数据:回显
  • 修改现有的数据:修改

第一部分回显:根据id显示值

service:

java 复制代码
public Product selectById(Long id){
    final SqlSession sqlSession = sqlSessionFactory.openSession();
    final ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
    final Product product = mapper.selectById(id);
    sqlSession.close();
    return product;
}

web:

java 复制代码
@WebServlet("/selectById")
public class SelectById extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String id = request.getParameter("id");
        ProductService productService = new ProductService();
        final Product product = productService.selectById(Long.parseLong(id));
        request.setAttribute("product",product);
        System.out.println(id);
        request.getRequestDispatcher("/jsp/productUpdate.jsp").forward(request,response);
    }
​
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

显示层:productUpdate.jsp

java 复制代码
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>修改</title>
  <style>
    .text {
      width: 100%;
    }
  </style>
</head>
<body>
<form action="/product_demo_war/updateById" method="post">
  <input type="hidden" name="id" value="${product.id}">
  <input class="text" type="text" name="title" placeholder="商品名称" value="${product.title}"><br>
  <input class="text" type="text" name="price" placeholder="商品价格" value="${product.price}"><br>
  <!--        图片上传在这里就先不写了-->
  <input class="text" type="number" name="category" placeholder="商品类型(数字就好)" value="${product.category}"><br>
  <c:if test="${product.status == 1}">
    <input type="radio" name="status" value="1" checked>启用
    <input type="radio" name="status" value="0">禁用
  </c:if>
  <c:if test="${product.status == 0}">
    <input type="radio" name="status" value="1">启用
    <input type="radio" name="status" value="0" checked>禁用
  </c:if>
​
  <br>
  <input type="submit" value="修改">
</form>
</body>
</html>

第二部分修改:

service:

java 复制代码
public void UpdateById(Product product){
    final SqlSession sqlSession = sqlSessionFactory.openSession();
    final ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
    mapper.updateById(product);
    sqlSession.commit();
}

servlet:

java 复制代码
@WebServlet("/updateById")
public class Update extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
​
        final Long id = Long.parseLong(request.getParameter("id"));
        final String title = request.getParameter("title");
        final String price = request.getParameter("price");
        final Integer category = Integer.parseInt(request.getParameter("category"));
        final Integer status = Integer.parseInt(request.getParameter("status"));
        Date gmtModified = new Date();
​
        Product product = new Product(id,title,price,category,status,gmtModified);
        ProductService productService = new ProductService();
        productService.UpdateById(product);
​
        request.getRequestDispatcher("/selectAll").forward(request,response);
​
    }
​
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

测试:

删除:不写了,jsp知道怎么写就行了

相关推荐
Lei活在当下10 小时前
【业务场景架构实战】4. 支付状态分层流转的设计和实现
架构·android jetpack·响应式设计
架构师沉默13 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
kfyty72516 小时前
不依赖第三方,不销毁重建,loveqq 框架如何原生实现动态线程池?
java·架构
刘立军18 小时前
本地大模型编程实战(33)用SSE实现大模型的流式输出
架构·langchain·全栈
一直_在路上18 小时前
Go 语言微服务演进路径:从小型项目到企业级架构
架构·go
_落纸21 小时前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
Alice-YUE1 天前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha1 天前
SpringBoot
笔记·学习
智能化咨询1 天前
Kafka架构:构建高吞吐量分布式消息系统的艺术——进阶优化与行业实践
分布式·架构·kafka
七夜zippoe1 天前
缓存与数据库一致性实战手册:从故障修复到架构演进
数据库·缓存·架构