MVC 模式和模型 2

MVC框架

一个实现 MVC 模式的应用包含模型、视图、控制器 3 个模块:

模型:封装了应用的数据和业务逻辑,负责管理系统业务数据

视图:负责应用的展示

控制器:负责与用户进行交互,接收用户输入、改变模型、调整视图的显示

基于MVC架构模式的 Java Web 开发

采用了 Servlet + JSP + JavaBean 的技术实现

基于MVC架构模式的 Java Web 开发步骤

1. 定义一系列的 Bean 来表示数据

2. 使用一个 Dispatcher Servlet 和控制类来处理用户请求

3. 在 Servlet 中填充 Bean

4. 在 Servlet 中,将 Bean 存储到 request、session、servletContext中

5. 将请求转发到 JSP 页面

6. 在 JSP 页面中,从 Bean 中提取数据。

其中 Dispatcher servlet 必须完成如下功能:

1. 根据 URI 调用相应的 action

2. 实例化正确的控制器类

3. 根据请求参数值来构造表单 bean

4. 调用控制器对象的相应方法

5. 转发到一个视图(JSP页面)

每个 HTTP 请求都发送给控制器,请求中的 URI 标识出对应的 action。action 代表了应用可以执行的一个操作。一个提供了 Action 的 Java 对象称为 action 对象。

控制器会解析 URI 并调用相应的 action,然后将模型对象放到视图可以访问的区域,以便服务器端数据可以展示在浏览器上。最后控制器利用 RequestDispatcher 跳转到视图(JSP页面),在JSP页面使用 EL 以及定制标签显示数据。

注意:调用 RequestDispatcher.forward 方法并不会停止执行剩余的代码。因此,若 forward 方法不是最后一行代码,则应显示的返回。

使用MVC模式的实例

 目录结构如下

代码如下

DispatcherServlet.java

package app16c.servlet;import java.io.IOException;import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import app16c.controller.InputProductController;
import app16c.controller.SaveProductController;@WebServlet(name = "DispatcherServlet", urlPatterns = {"/product_input.action", "/product_save.action"})
public class DispatcherServlet extends HttpServlet {private static final long serialVersionUID = 1L;public DispatcherServlet() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {process(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String uri = request.getRequestURI();int lastIndex = uri.lastIndexOf("/");String action = uri.substring(lastIndex + 1);String dispatcherUrl = null;if (action.equals("product_input.action")) {InputProductController controller = new InputProductController();dispatcherUrl = controller.handleRequest(request, response);} else if (action.equals("product_save.action")) {SaveProductController controller = new SaveProductController();dispatcherUrl = controller.handleRequest(request, response);}if (dispatcherUrl != null) {RequestDispatcher rd = request.getRequestDispatcher(dispatcherUrl);rd.forward(request, response);}}
}

Controller.java

package app16c.controller;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public interface Controller {public abstract String handleRequest(HttpServletRequest request, HttpServletResponse response);
}

InputProductController.java

package app16c.controller;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class InputProductController implements Controller {@Overridepublic String handleRequest(HttpServletRequest request, HttpServletResponse response) {return "/WEB-INF/jsp/ProductForm.jsp";}
}

SaveProductController.java

package app16c.controller;import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import app16c.domain.Product;
import app16c.form.ProductForm;
import app16c.validator.ProductValidator;public class SaveProductController implements Controller {@Overridepublic String handleRequest(HttpServletRequest request, HttpServletResponse response) {ProductForm productForm = new ProductForm();productForm.setName(request.getParameter("name"));productForm.setDescription(request.getParameter("description"));productForm.setPrice(request.getParameter("price"));ProductValidator productValidator = new ProductValidator();List<String> errors = productValidator.validate(productForm);System.out.println(errors);if (errors.isEmpty()) {Product product = new Product();product.setName(productForm.getName());product.setDescription(productForm.getDescription());product.setPrice(Float.parseFloat(productForm.getPrice()));// insert code to save product to the databaserequest.setAttribute("product", product);return "/WEB-INF/jsp/ProductDetails.jsp";} else {request.setAttribute("errors", errors);request.setAttribute("form", productForm);return "/WEB-INF/jsp/ProductForm.jsp";}}
}

ProductValidator.java

package app16c.validator;import java.util.ArrayList;
import java.util.List;
import app16c.form.ProductForm;public class ProductValidator {public List<String> validate(ProductForm productForm) {List<String> errors = new ArrayList<>();String name = productForm.getName();if (name == null || name.trim().isEmpty()) {errors.add("Product must have a name");}String price = productForm.getPrice();if (price == null || price.trim().isEmpty()) {errors.add("Product must have a price");}else {try {Float.parseFloat(price);} catch (NumberFormatException e) {errors.add("Invalid price value.");}}return errors;}
}

Product.java

package app16c.domain;import java.io.Serializable;public class Product implements Serializable { // 一个JavaBean 实现该接口,其实例可以安全的将数据保存到 HttpSession 中。private static final long serialVersionUID = 1L;private String name;private String description;private float price;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}
}

ProductForm.java

package app16c.form;// 表单类与 HTML表单相映射,是HTML表单在服务端的代表
public class ProductForm {  // 表单类不需要实现 Serializable 接口,因为表单对象很少保存在 HttpSession 中。private String name;private String description;private String price;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}
}

ProductForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  <!-- taglib指令用来引用标签库并设置标签库的前缀  --><!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Add Product Form</title><link rel="stylesheet" type="text/css" href="css/main.css" />  <!-- 外部样式表 -->
</head>
<body><div id="global"><c:if test="${requestScope.errors != null }">  <!-- EL表达式 --><p id="errors">Error(s)!<ul><c:forEach var="error" items="${requestScope.errors }">  <!-- jstl 遍历 --><li>${error }</li></c:forEach></ul></p></c:if><form action="product_save.action" method="post"><fieldset><legend>Add a product</legend><p><label for="name">Product Name: </label><input type="text" id="name" name="name" tabindex="1" /></p><p><label for="description">Description: </label><input type="text" id="description" name="description" tabindex="2" /></p><p><label for="price">Price: </label><input type="text" id="price" name="price" tabindex="3" /></p><p id="buttons"><input id="reset" type="reset" tabindex="4" /><input id="submit" type="submit" tabindex="5" value="Add Product" /></p></fieldset></form></div>
</body>
</html>

ProductDetails.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Save Product</title><link rel="stylesheet" type="text/scc" href="css/main.css" />
</head>
<body><div id="global"><h4>The product has been saved.</h4><p><h5>Details</h5>Product Name: ${product.name } <br />Description: ${product.description } <br />Price: $${product.price }</p></div>
</body>
</html>

测试结果

 

转载于:https://www.cnblogs.com/0820LL/p/9949873.html

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

splite和map的结合使用

split() 方法用于把一个字符串分割成字符串数组。 Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。 作用&#xff1a;分割出来的字符串储存在map对象(key,value)中&#xff0c;便于前后台使用。 Map<String, Object> paramMap new HashMap<S…

Delphi与各数据库数据类型比较

Delphi数据类型与各数据库数据类型对比如下表&#xff0c;如有具体说明见表中脚注&#xff1a; Delphi Type Oracle Types SQL Server Types MySQL Types [1] InterBase Types PostgreSQL Types SQLite Types ftSmallint NUMBER(p, 0)[2] (p < 5) SMALLINT …

mybatis foreach collection

foreach的主要用在构建in条件中&#xff0c;它可以在SQL语句中进行迭代一个集合。 foreach元素的属性主要有 item&#xff0c;index&#xff0c;collection&#xff0c;open&#xff0c;separator&#xff0c;close。 item表示集合中每一个元素进行迭代时的别名&#xff0c;in…

Java中线程池,你真的会用吗?

在《深入源码分析Java线程池的实现原理》这篇文章中&#xff0c;我们介绍过了Java中线程池的常见用法以及基本原理。 在文中有这样一段描述&#xff1a; 可以通过Executors静态工厂构建线程池&#xff0c;但一般不建议这样使用。 关于这个问题&#xff0c;在那篇文章中并没有深…

java (lodop) 打印实例

首先在lodop官网下载相关文件&#xff08;js、css等&#xff09;&#xff1a;http://www.lodop.net/download.html 在下载好的包里 除了html页面 其他的js、css等拷贝到项目的一个目录下、新建个lodop文件夹。 lodop主要接口函数如下&#xff1a; ● PRINT_INIT(strPrintTaskN…

深入了解java虚拟机(JVM) 第四章 对象的创建

一、对象的创建过程 对象的创建过程大致可以分为六步&#xff0c;其中对象的分配尤为重要&#xff1a; 二、对象分配内存 一般来说对象分配内存有两种方式&#xff1a; 第一种是指针碰撞&#xff0c;这是一种比较理想的方式&#xff1a;如果Java堆是绝对规整的&#xff1a;一边…

LODOP使用问题解决汇总

LODOP 打印控件出现问题及修改方法 问题1 、打印网页时页面出现电脑设置的底色如何解决&#xff1f; 解决方法 &#xff1a;按照如下方式添加HTML页面 var strHTML"<body stylemargin:0;background-color: white>"document.getElementById("table02&qu…

[UWP]使用Picker实现一个简单的ColorPicker弹窗

[UWP]使用Picker实现一个简单的ColorPicker弹窗 原文:[UWP]使用Picker实现一个简单的ColorPicker弹窗在上一篇博文《[UWP]使用Popup构建UWP Picker》中我们简单讲述了一下使用Popup构建适用于MVVM框架下的弹窗层组件Picker的过程。但是没有应用实例的话可能体现不出Picker相对于…

java sort排序

问题&#xff1a;对list中的对象中的属性值排序&#xff1a; User对象&#xff1a; public class User {private int id;private String Name; public int getid() {return id;}public void setid(int id) {this.id id;}public String getName() {return Name;}pub…

C# WebRequest.Create 锚点“#”字符问题

背景 在与后台API接口对接时&#xff0c;如将网页Url作为参数请求数据时&#xff0c;如果是锚点参数&#xff0c;则会丢失。 锚点参数 请求通过WebRequest.Create创建一个WebRequest&#xff1a; 1 var uri "https://id.test.xxx.com/api/v1/auth/sso/url?redirectUrlht…

Postgresql 按30分钟、小时、天分组

按30分钟统计&#xff1a; shool_time格式为varchar&#xff0c; 例如 201911050808、201911050820、201911050842 分组后结果&#xff1a; 20191105 0800 20191105 0830 20191105 0900 20191105 0930 注&#xff1a;小于30分钟的按00统计&#xff0c;大于30分钟的按30统计 SEL…

Java calendar加减时间

//时间格式可以改成自己想要的格式&#xff0c;例yyyy-MM-dd HH:mm等等。 private final static String formatyyyyMMddHHMM "yyyyMMddHHmm";String currTime "201911051500";SimpleDateFormat yearFormat new SimpleDateFormat(formatyyyyMMddHHMM); D…

免费的编程中文书籍索引(2018第三版)

之前我在 github 上整理了来一份&#xff1a;free-programming-books-zh_CN&#xff08;免费的计算机编程类中文书籍&#xff09;。 截至目前为止&#xff0c;已经在 GitHub 收获了 40000 多的 stars&#xff0c;有 90 多人发了 600 多个 Pull Requests 和 issues。 在收集的过…

java中Map ListE的用法

返回的restful接口数据样式&#xff1a; {party: [{"finishTime": "20191105","busiCnt": 1000}]}1、定义WzwScreenEntity 实体 public class WzwScreenEntity {private String finishTime;private String busiCnt;private String party;publi…

ORM是什么?如何理解ORM?

一、ORM简介 对象关系映射&#xff08;Object Relational Mapping&#xff0c;简称ORM&#xff09;模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说&#xff0c;ORM是通过使用描述对象和数据库之间映射的元数据&#xff0c;将程序中的对象…

遍历Map keySet和entrySet

public class test {public static void main(String[] args) {Map<String, String> map new HashMap<String, String>();map.put("1", "广东");map.put("2", "广西");map.put("3", "广南");map.put…

falcon适配ldap密码同步

问题 小米的openfalcon在使用ldap首次登陆成功后,会在本地创建同名的账号, 这就有个问题当你更新了ldap的密码时,openfalcon是没有同步本地账号密码的功能 二次改造 方便我们debug, 先把日志的debug打开,默认是没有运行时日志的,只有console日志 # 编辑文件 dashboard/rrd/util…

如何有效的使用 for循环和Iterator遍历

遍历ArrayList 使用for循环遍历的速度会比Iterator遍历的速度要快&#xff1a; for (int i0, nlist.size(); i < n; i)list.get(i);runs faster than this loop:for (Iterator ilist.iterator(); i.hasNext();)i.next();采用ArrayList对随机访问比较快&#xff0c;而for循环…

【js】数组置空的其他方式及使用场景

数组在js中属于引用型类型。 var arr [1, 2, 3]; a []; 通常使用以上方式。如果使用场景必须使用方法置空&#xff0c; 可以采用arr.length 0; 或者使用a.splice(0, a.length); 使用场景 vue2中组定义组件中v-model的值是数组类型&#xff0c; 组件内部需要清空时&#xff0…

Postgresql 填充所有的时间点

最近使用有个业务需要展示20190101和20190106所有的时间段&#xff0c;例如 20190101 20190102 20190103 20190104 20190105 20190106但是数据库中存的只有以下 20190101 20190102 20190104 20190106那我们需要把20190103、20190105填充进去。 方式一&#xff1a; 新建个存储…