MVC 模式和模型 2
MVC框架
一個(gè)實(shí)現(xiàn) MVC 模式的應(yīng)用包含模型、視圖、控制器 3 個(gè)模塊:
模型:封裝了應(yīng)用的數(shù)據(jù)和業(yè)務(wù)邏輯,負(fù)責(zé)管理系統(tǒng)業(yè)務(wù)數(shù)據(jù)
視圖:負(fù)責(zé)應(yīng)用的展示
控制器:負(fù)責(zé)與用戶(hù)進(jìn)行交互,接收用戶(hù)輸入、改變模型、調(diào)整視圖的顯示
基于MVC架構(gòu)模式的 Java Web 開(kāi)發(fā)
采用了 Servlet + JSP + JavaBean 的技術(shù)實(shí)現(xiàn)
基于MVC架構(gòu)模式的 Java Web 開(kāi)發(fā)步驟
1. 定義一系列的 Bean 來(lái)表示數(shù)據(jù)
2. 使用一個(gè) Dispatcher Servlet 和控制類(lèi)來(lái)處理用戶(hù)請(qǐng)求
3. 在 Servlet 中填充 Bean
4. 在 Servlet 中,將 Bean 存儲(chǔ)到 request、session、servletContext中
5. 將請(qǐng)求轉(zhuǎn)發(fā)到 JSP 頁(yè)面
6. 在 JSP 頁(yè)面中,從 Bean 中提取數(shù)據(jù)。
其中 Dispatcher servlet 必須完成如下功能:
1. 根據(jù) URI 調(diào)用相應(yīng)的 action
2. 實(shí)例化正確的控制器類(lèi)
3. 根據(jù)請(qǐng)求參數(shù)值來(lái)構(gòu)造表單 bean
4. 調(diào)用控制器對(duì)象的相應(yīng)方法
5. 轉(zhuǎn)發(fā)到一個(gè)視圖(JSP頁(yè)面)
每個(gè) HTTP 請(qǐng)求都發(fā)送給控制器,請(qǐng)求中的 URI 標(biāo)識(shí)出對(duì)應(yīng)的 action。action 代表了應(yīng)用可以執(zhí)行的一個(gè)操作。一個(gè)提供了 Action 的 Java 對(duì)象稱(chēng)為 action 對(duì)象。
控制器會(huì)解析 URI 并調(diào)用相應(yīng)的 action,然后將模型對(duì)象放到視圖可以訪問(wèn)的區(qū)域,以便服務(wù)器端數(shù)據(jù)可以展示在瀏覽器上。最后控制器利用 RequestDispatcher 跳轉(zhuǎn)到視圖(JSP頁(yè)面),在JSP頁(yè)面使用 EL 以及定制標(biāo)簽顯示數(shù)據(jù)。
注意:調(diào)用 RequestDispatcher.forward 方法并不會(huì)停止執(zhí)行剩余的代碼。因此,若 forward 方法不是最后一行代碼,則應(yīng)顯示的返回。
使用MVC模式的實(shí)例
?目錄結(jié)構(gòu)如下
代碼如下
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 { // 一個(gè)JavaBean 實(shí)現(xiàn)該接口,其實(shí)例可以安全的將數(shù)據(jù)保存到 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;// 表單類(lèi)與 HTML表單相映射,是HTML表單在服務(wù)端的代表 public class ProductForm { // 表單類(lèi)不需要實(shí)現(xiàn) Serializable 接口,因?yàn)楸韱螌?duì)象很少保存在 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指令用來(lái)引用標(biāo)簽庫(kù)并設(shè)置標(biāo)簽庫(kù)的前綴 --><!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表達(dá)式 --><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>測(cè)試結(jié)果
?
轉(zhuǎn)載于:https://www.cnblogs.com/0820LL/p/9949873.html
總結(jié)
以上是生活随笔為你收集整理的MVC 模式和模型 2的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 深度学习入门|第5章 误差反向传播法(二
- 下一篇: BZOJ4520 CQOI2016K远点