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知道怎么写就行了

相关推荐
群联云防护小杜9 分钟前
构建分布式高防架构实现业务零中断
前端·网络·分布式·tcp/ip·安全·游戏·架构
森焱森42 分钟前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
I'm写代码2 小时前
el-tree树形结构笔记
javascript·vue.js·笔记
wenzhangli72 小时前
从源码到思想:OneCode框架模块化设计如何解决前端大型应用痛点
架构·前端框架
秋千码途3 小时前
小架构step系列07:查找日志配置文件
spring boot·后端·架构
Andy杨3 小时前
20250707-4-Kubernetes 集群部署、配置和验证-K8s基本资源概念初_笔记
笔记·容器·kubernetes
Ashlee_code5 小时前
什么是Web3?金融解决方案
开发语言·金融·架构·eclipse·web3·区块链·php
UQI-LIUWJ5 小时前
李宏毅LLM笔记: AI Agent
人工智能·笔记
ouliten5 小时前
cuda编程笔记(6)--流
笔记
Love__Tay5 小时前
笔记/云计算基础
笔记·学习·云计算