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();@Overrideprotected 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);}
​@Overrideprotected 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: LEGIONDate: 2024/3/13Time: 13:36To 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 {@Overrideprotected 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);}
​@Overrideprotected 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 {@Overrideprotected 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);}
​@Overrideprotected 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 {@Overrideprotected 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);
​}
​@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}

测试:

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

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

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

线性回归 quickstart

构建一元一次方程 100个&#xff08;X, y &#xff09;&#xff0c;大概是’y3x4’ import numpy as npnp.random.seed(42) # to make this code example reproducible m 100 # number of instances X 2 * np.random.rand(m, 1) # column vector y 4 3 * X np.random…

Fork - 将 GitHub 的某个特定仓库复制到自己的账户下

Fork - 将 GitHub 的某个特定仓库复制到自己的账户下 1. ForeverStrongCheng/OpenCV-tutorials2. Fork -> ForeverStrongCheng/R2CNN_Faster-RCNN_TensorflowReferences 访问仓库页面&#xff0c;点击 Fork 按钮创建自己的仓库。 Fork 是将 GitHub 的某个特定仓库复制到自己…

Qt 实现 Asterix 报文解析库

【写在前面】 最近工作中需要解析 Cat 21 和 Cat 62 的 ADS-B 数据 ( 自己的工作包含航空领域 )。 然后&#xff0c;因为整个 Asterix 协议类别非常之多&#xff0c;每个类别的版本也多&#xff0c;纯手工实现每个版本解析根本不现实 ( 然鹅公司之前的解析库就是这么做的且做的…

面试官:volatile如何保证可见性的,具体如何实现?

写在开头 在之前的几篇博文中&#xff0c;我们都提到了 volatile 关键字&#xff0c;这个单词中文释义为&#xff1a;不稳定的&#xff0c;易挥发的&#xff0c;在Java中代表变量修饰符&#xff0c;用来修饰会被不同线程访问和修改的变量&#xff0c;对于方法&#xff0c;代码…

前端之用HTML弄一个古诗词

将进酒 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>将进酒</title><h1><big>将进酒</big> 君不见黄河之水天上来</h1><table><tr><td ><img…

【逆向-快速定位关键代码】通过hook常用函数HashMap方法

一生要走多远的路程 经过多少年 才能走到终点 梦想需要多久的时间 多少血和泪 才能慢慢实现 天地间任我展翅高飞 谁说那是天真的预言 &#x1f3b5; Beyond《光辉岁月》 随着移动应用程序的普及&#xff0c;对于安全和隐私的关注也越来越高。安卓应用逆向…

【力扣白嫖日记】1934.确认率

前言 练习sql语句&#xff0c;所有题目来自于力扣&#xff08;https://leetcode.cn/problemset/database/&#xff09;的免费数据库练习题。 今日题目&#xff1a; 1934.确认率 表&#xff1a;Signups 列名类型user_idinttime_stampdatetime User_id是该表的主键。每一行都…

JUC之Java对象内存布局

Java对象 对象在堆中的存储布局 它保存了什么 对象指向它的类元数据的指针&#xff0c;虚拟机通过这个指针来确定这个对象是哪个类的实例 对象头有多大&#xff1f;在64位系统中&#xff0c;Mark Word占了8个字节&#xff0c;类型指针占了8个字节&#xff0c;一共是16个字…

鸿蒙开发实现弹幕功能

鸿蒙开发实现弹幕功能如下&#xff1a; 弹幕轮播组件&#xff1a;BannerScroll import type { IDanMuInfoList, IDanMuInfoItem } from ../model/DanMuData //定义组件 Component export default struct BannerScroll {//Watch 用来监视状态数据的变化&#xff0c;包括&#…

git:码云仓库提交以及Spring项目创建

git&#xff1a;码云仓库提交 1 前言 码云访问稳定性优于github&#xff0c;首先准备好码云的账户&#xff1a; 官网下载GIT&#xff0c;打开git bash&#xff1a; 查看当前用户的所有GIT仓库&#xff0c;需要查看全局的配置信息&#xff0c;使用如下命令&#xff1a; git …

Navicat 面试题及答案整理,最新面试题

Navicat 在数据库管理中的主要用途有哪些&#xff1f; Navicat 是一款数据库管理工具&#xff0c;其主要用途包括&#xff1a; 1、多数据库支持&#xff1a; Navicat 支持多种数据库连接&#xff0c;包括 MySQL、Oracle、PostgreSQL、SQLite、SQL Server 等&#xff0c;方便用…

深度强化学习(五)(蒙特卡洛与自举)

深度强化学习&#xff08;五&#xff09;&#xff08;蒙特卡洛与自举&#xff09; 一.蒙特卡洛与自举 上一节介绍了多步 TD 目标。单步 TD 目标、回报是多步 TD 目标的两种特例。如下图所示, 如果设 m 1 m1 m1, 那么多步 TD 目标变成单步 T D \mathrm{TD} TD 目标。如果设…

compile→错误: 不支持发行版本 17

错误: 不支持发行版本 17 具体错误描述如下&#xff1a; [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.11.0:compile (default-compile) on project big-event: Fatal error compiling: 错误: 不支持发行版本 17 -> [Help 1] [ERROR] …

Chapter 13 Techniques of Design-Oriented Analysis: The Feedback Theorem

Chapter 13 Techniques of Design-Oriented Analysis: The Feedback Theorem 从这一章开始讲负反馈Control系统和小信号建模. 13.2 The Feedback Theorem 首先介绍 Middlebrook’s Feedback Theorem 考虑下面负反馈系统 传输函数 Guo/ui G ( s ) u o u i G ∞ T 1 T G…

Artemis Finance引领Metis流动性质押,并启动积分空投活动

在以太坊可扩展性解决方案中&#xff0c; Optimism、Arbitrum等Layer2链主要面临两个问题&#xff1a;欺诈/有效性证明以及去中心化排序器Sequencers。在实际的发展过程中&#xff0c;Optimism或Arbitrum等Layer2链仍然侧重于在欺诈证明和有效性证明方面进行努力&#xff0c;在…

2024年AI辅助研发趋势

标题 《2024年AI辅助研发趋势》摘要 &#x1f680;引言 &#x1f31f;技术进展&#xff1a;AI在研发中的革命性应用 &#x1f4a1;行业应用案例&#xff1a;AI助力解决复杂研发难题 &#x1f3ed;面临的挑战与机遇&#xff1a;化解难题迎接未来 &#x1f6e0;️未来趋势预测&am…

在命令行中输入py有效,输入python无效,输入python会跳转到microsoft store

这里写自定义目录标题 如果你已经尝试过将python添加到系统变量如果你还未将python添加到系统变量没有python安装包且没有配置系统变量 如果你已经尝试过将python添加到系统变量 打开 运行&#xff0c;输入cmd&#xff0c;在命令行中输入 where python。 如果看到了这个 win…

【海贼王的数据航海】排序——概念|直接插入排序|希尔排序

目录 1 -> 排序的概念及其运用 1.1 -> 排序的概念 1.2 -> 常见的排序算法 2 -> 插入排序 2.1 -> 基本思想 2.2 -> 直接插入排序 2.2.1 -> 代码实现 2.3 -> 希尔排序(缩小增量排序) 2.3.1 -> 代码实现 1 -> 排序的概念及其运用 1.1 -&g…

C++ //练习 10.35 使用普通迭代器逆序打印一个vector。

C Primer&#xff08;第5版&#xff09; 练习 10.35 练习 10.35 使用普通迭代器逆序打印一个vector。 环境&#xff1a;Linux Ubuntu&#xff08;云服务器&#xff09; 工具&#xff1a;vim 代码块 /********************************************************************…

vue学习笔记26-插槽Slots

插槽Slots 组件接收模板内容&#xff08;html结构&#xff09;&#xff0c;在某些场景中我们想要为子组件传递一些模板片段。让子组件在它们的组件中渲染这些片段 将子组件在父组件引用后&#xff0c;比以往更改一下,将<子组件名/>➡️<子组件名></子组件名&g…