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包下

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包下

@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:

<%@ 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

<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:

/**
 * 添加商品
 * @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:

@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:

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:

@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

<%@ 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:

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

servlet:

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/455546.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

雅特力AT32A403开发板评测 01 开箱及环境搭建流程

01-雅特力AT32A403A开发板开箱及环境搭建流程 雅特力AT32 2023年&#xff0c;玩了不少的国产MCU开发板&#xff0c;例如武汉芯源CW32&#xff0c;兆易创新GD32、上海航芯ACM32、沁恒CH32V307等开发板&#xff0c;虽然电子工程世界论坛也有雅特力AT32开发板的评测活动&#xf…

NO5 蓝桥杯实践之矩阵键盘的使用(或许是一篇求助帖...)

1 任务 2 思路 视频中老师的思路写的代码过长&#xff0c;所以我想了个自己的思路&#xff0c;但是没完全跑出来&#xff0c;求大神指教&#xff01;&#xff01;&#xff01;&#xff01; 我的思路是首先将矩阵键盘的行和列对应的端口引脚分别存储在类似数组&#xff0c;然后…

人工智能|机器学习——BIRCH聚类算法(层次聚类)

这里再来看看另外一种常见的聚类算法BIRCH。BIRCH算法比较适合于数据量大&#xff0c;类别数K也比较多的情况。它运行速度很快&#xff0c;只需要单遍扫描数据集就能进行聚类。 1.什么是流形学习 BIRCH的全称是利用层次方法的平衡迭代规约和聚类&#xff08;Balanced Iterative…

环形缓冲区在stm32上的使用

目录 环形缓冲区在stm32上的使用前言实验目的环形缓冲区的定义和初始化写入数据到环形缓冲区从环形缓冲区读取数据实验结果本文中的实践工程 环形缓冲区在stm32上的使用 本文目标&#xff1a;环形缓冲区在stm32上的使用 按照本文的描述&#xff0c;应该可以跑通实验并举一反三…

利用Anaconda创建环境

利用Anaconda创建环境 1. 创建环境的步骤 1. 创建环境的步骤 1.在终端中&#xff0c;使用以下命令创建一个新的 Anaconda 环境。假设您想要创建一个名为 myenv 的环境&#xff1a; conda create --name myenv2.如果您想指定 Python 版本&#xff0c;可以在创建环境时添加版本号…

AI论文速读 | 计时器(Timer):用于大规模时间序列分析的Transformer

题目&#xff1a; Timer: Transformers for Time Series Analysis at Scale 作者&#xff1a;Yong Liu,&#xff08;刘雍&#xff09;, Haoran Zhang&#xff08;张淏然&#xff09;, Chenyu Li&#xff08;李晨宇&#xff09;, Jianmin Wang&#xff08;王建民&#xff09;, …

群晖 Synology Photos DSM7 自定义文件夹管理照片

背景 众所周知&#xff0c;目前群晖DSM7中使用Synology Photos做照片管理时&#xff0c;个人照片只能默认索引 /home/Photos 文件夹&#xff0c;但是如果个人照片很多或者用户很多时&#xff0c;共享文件夹/homes 所在的存储空间就会不够用 当然&#xff0c;如果你的存…

【软考高项】四、信息化发展之数字中国

1、数字经济 定义&#xff1a;从本质上看&#xff0c;数字经济是一种新的技术经济范式&#xff0c;它建立在信息与通信技术的重大突破的基础上&#xff0c;以数字技术与实体经济融合驱动的产业梯次转型和经济创新发展的主引擎&#xff0c;在基础设施、生产要素、产业结构和治理…

certificate has expired or is not yet valid:npm和node证书过期问题

在 1 月 22 日&#xff0c;淘宝原镜像域名&#xff08;registry.npm.taobao.org&#xff09;的 HTTPS 证书正式到期。如果想要继续使用&#xff0c;需要将 npm 源切换到新的源&#xff08;registry.npmmirror.com&#xff09;&#xff0c;否则会报错。 解决方案切换到新的源&a…

nacos做注册注册中心go语言实战教程(服务的注册与获取)

背景 随着访问量的逐渐增大&#xff0c;单体应用结构渐渐不满足需求&#xff0c;在微服务出现之后引用被拆分为一个个的服务&#xff0c;服务之间可以互相访问。初期服务之间的调用只要知道服务地址和端口即可&#xff0c;而服务会出现增减、故障、升级等变化导致端口和ip也变…

欧科云链做客Google Cloud与WhalerDAO专题论坛,畅谈Web3数据机遇

3月10日&#xff0c;由Google Cloud、WhalerDAO和baidao data主办&#xff0c;以Web3AI 2024 DATA POWER为主题的分享会在北京中关村举行。欧科云链高级研究员Jason Jiang受邀参加活动&#xff0c;带来“从链上数据发掘Web3时代的无限机遇”的主题分享。 Web3.0核心要素始终是链…

如何从 Mac 电脑外部硬盘恢复删除的数据文件

本文向您介绍一些恢复 Mac 外置硬盘数据的快速简便的方法。 Mac 的内部存储空间通常不足以存储所有数据。因此&#xff0c;许多用户通过外部驱动器扩展存储或创建数据备份。然而&#xff0c;与几乎所有其他设备一样&#xff0c;从外部硬盘驱动器丢失有价值的数据并不罕见。由于…

第二证券|炒股最好用的6个指标?

炒股存在以下好用的6个目标&#xff1a; 1、kdj目标 当k线从下方往上穿过d线时&#xff0c;构成金叉&#xff0c;是一种买入信号&#xff0c;投资者能够考虑在此刻买入一些个股&#xff0c;其间kdj金叉方位越低&#xff0c;买入信号越强&#xff1b;当k线从上往下穿过d线时&a…

HTML静态网页成品作业(HTML+CSS)——电影肖申克的救赎介绍设计制作(1个页面)

&#x1f389;不定期分享源码&#xff0c;关注不丢失哦 文章目录 一、作品介绍二、作品演示三、代码目录四、网站代码HTML部分代码 五、源码获取 一、作品介绍 &#x1f3f7;️本套采用HTMLCSS&#xff0c;未使用Javacsript代码&#xff0c;共有1个页面。 二、作品演示 三、代…

“SRP模型+”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展应用教程

原文链接&#xff1a;“SRP模型”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展应用教程https://mp.weixin.qq.com/s?__bizMzUzNTczMDMxMg&mid2247597452&idx5&snf723d9e5858a269d00e15dbe2c7d3dc0&chksmfa823c6…

Python算法(列表排序)

一。冒泡排序&#xff1a; 列表每两个相邻的数&#xff0c;如果前面比后面大&#xff0c;则交换这两个数 一趟排序完成后&#xff0c;则无序区减少一个数&#xff0c;有序区增加一个数 时间复杂度&#xff1a;O(n*n) 优化后&#xff1a;已经排序好后立马停止&#xff0c;加快…

Ubuntu 14.04:PaddleOCR基于PaddleHub Serving的服务部署(失败)

目录 一、为什么使用一键服务部署 二、安装 paddlehub 1.8 2.1 安装前的环境准备 2.2 安装paddlehub 1.8 2.2.1 安装paddlehub 2.2.2 检测安装是否成功 2.2.3 检查本地与远端PaddleHub-Server的连接状态 2.2.4 测试使用 2.3 其他 2.3.1 如何卸载、pip常用命令、常见…

FPGA高端项目:FPGA基于GS2971+GS2972架构的SDI视频收发+HLS图像缩放+多路视频拼接,提供4套工程源码和技术支持

目录 1、前言免责声明 2、相关方案推荐本博已有的 SDI 编解码方案本方案的SDI接收发送本方案的SDI接收图像缩放应用本方案的SDI接收纯verilog图像缩放纯verilog多路视频拼接应用本方案的SDI接收OSD动态字符叠加输出应用本方案的SDI接收HLS多路视频融合叠加应用本方案的SDI接收G…

Pandas DataFrame 写入 Excel 的三种场景及方法

一、引言 本文主要介绍如何将 pandas 的 DataFrame 数据写入 Excel 文件中&#xff0c;涉及三个不同的应用场景&#xff1a; 单个工作表写入&#xff1a;将单个 DataFrame 写入 Excel 表中&#xff1b;多个工作表写入&#xff1a;将多个 DataFrame 写入到同一个 Excel 表中的…

2024考研计算机考研复试-每日重点(第十九期)

公众号“准研计算机复试”&#xff0c;超全大佬复试资料&#xff0c;保姆级复试&#xff0c;80%的题目都是上岸大佬提供的。 研宝们&#xff0c;App更新啦&#xff01; 操作系统&#xff1a; 10.★什么是中断&#xff1f; 中断是指计算机运行过程中&#xff0c;出现某些意外时…