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
總結
以上是生活随笔為你收集整理的MVC 模式和模型 2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度学习入门|第5章 误差反向传播法(二
- 下一篇: C++实现二叉树的相应操作