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 分钟前
40㎡客厅变形记,小家住出大自由[特殊字符]
android·经验分享·笔记·智能家居·微信公众平台
摇滚侠12 分钟前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 数据库初始化机制 阅读笔记 36
数据库·spring boot·笔记
商业看点解说1 小时前
企业要统一接入OpenAI/Claude/DeepSeek选择哪款云平台更合适?Amazon Bedrock 将三类模型整合进一套企业 AI 架构
架构
推送者2 小时前
用宠物照片制作桌宠:从AI拆帧到九点标定的本地化实现笔记
笔记·宠物·用宠物照片制作桌宠
一条破秋裤3 小时前
16_TIM编码器接口测速
笔记·stm32·学习
tju新生代魔迷3 小时前
Verilog HDL 学习笔记(十)| 第10章 时序和延迟
笔记·学习·fpga开发
javaDocker3 小时前
电视台自建AI短视频生产线与算力底座:技术架构、关键实现与优化实践
人工智能·架构·音视频
haishikeji696_4 小时前
市域空中智能治理建设:无人机巡检管控平台功能架构与行业落地方案
架构·无人机·低空经济·无人机巡检·无人机管理系统·飞控管理平台
血小板要健康4 小时前
链表 阶段算法总结
java·数据结构·笔记·算法·leetcode·链表
浔溺5 小时前
al+大数据每日学习笔记31
大数据·笔记·学习