什么是MVC框架

MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,
   它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,其好处是将业务逻辑聚集到一个部件里面,在改进和指定个性化页面的同时不需要重新编写业务逻    辑,MVC被独特的发展起来用于映射传统的输入,处理,显示在一个业务逻辑的图形化业务界面中。

核心思想:各司其职

  注1:不能跨层调用
  注2:只能出现由上而下的调用

MVC工作原理图:

主控制(ActionServlet)动态调用子控制器(Action)调用完成具体的业务逻辑(火车、控制台、车轨)请求、主控制器、子控制器

具体代码如下:

1,导入需要用到的jar包

2、mvc.xml建模     将Action的信息配置到xml(反射实例化)

解决了在框架代码中去改动,以便于完成客户需求,在框架中更改代码是不合理的

mvc.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
     
    <config>
     
     
     <!-- <action path="/addCal" type="com.yuan.web.AddCalAction">
      <forward name="res" path="/res.jsp" redirect="false" />
     </action>
     
     <action path="/delCal" type="com.yuan.web.DelCalAction">
      <forward name="res" path="/res.jsp" redirect="true"/>
     </action>  -->
     
     
      <action path="/cal" type="com.yuan.web.CalAction">
      <forward name="res" path="/res.jsp" redirect="false"/>
     </action>
  2.  
  3. </config>

ForwardModel

  1. package com.yuan.framework;
  2.  
  3. import java.io.Serializable;
  4.  
  5. /**
  6. * 用来描述forward标签
  7. * @author Administrator
  8. *
  9. */
  10. public class ForwardModel implements Serializable {
  11.  
  12. private static final long serialVersionUID = -8587690587750366756L;
  13.  
  14. private String name;
  15. private String path;
  16. private String redirect;
  17.  
  18. public String getName() {
  19. return name;
  20. }
  21.  
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25.  
  26. public String getPath() {
  27. return path;
  28. }
  29.  
  30. public void setPath(String path) {
  31. this.path = path;
  32. }
  33.  
  34. public String getRedirect() {
  35. return redirect;
  36. }
  37.  
  38. public void setRedirect(String redirect) {
  39. this.redirect = redirect;
  40. }
  41.  
  42. }

ActionModel

  1. package com.yuan.framework;
  2.  
  3. import java.io.Serializable;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. /**
  8. * 用来描述action标签
  9. * @author Administrator
  10. *
  11. */
  12. public class ActionModel implements Serializable{
  13.  
  14. private static final long serialVersionUID = 6145949994701469663L;
  15.  
  16. private Map<String, ForwardModel> forwardModels = new HashMap<String, ForwardModel>();
  17.  
  18. private String path;
  19.  
  20. private String type;
  21.  
  22. public String getPath() {
  23. return path;
  24. }
  25.  
  26. public void setPath(String path) {
  27. this.path = path;
  28. }
  29.  
  30. public String getType() {
  31. return type;
  32. }
  33.  
  34. public void setType(String type) {
  35. this.type = type;
  36. }
  37.  
  38. public void put(ForwardModel forwardModel){
  39. forwardModels.put(forwardModel.getName(), forwardModel);
  40. }
  41.  
  42. public ForwardModel get(String name){
  43. return forwardModels.get(name);
  44. }
  45.  
  46. }

ConfigModel

  1. package com.yuan.framework;
  2.  
  3. import java.io.Serializable;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. /**
  8. * 用来描述config标签
  9. * @author Administrator
  10. *
  11. */
  12. public class ConfigModel implements Serializable{
  13.  
  14. private static final long serialVersionUID = -2334963138078250952L;
  15.  
  16. private Map<String, ActionModel> actionModels = new HashMap<String, ActionModel>();
  17.  
  18. public void put(ActionModel actionModel){
  19. actionModels.put(actionModel.getPath(), actionModel);
  20. }
  21.  
  22. public ActionModel get(String name){
  23. return actionModels.get(name);
  24. }
  25.  
  26. }

ConfigModelFactory

  1. package com.yuan.framework;
  2.  
  3. import java.io.InputStream;
  4. import java.util.List;
  5.  
  6. import org.dom4j.Document;
  7. import org.dom4j.Element;
  8. import org.dom4j.io.SAXReader;
  9.  
  10. public class ConfigModelFactory {
  11. private ConfigModelFactory() {
  12.  
  13. }
  14.  
  15. private static ConfigModel configModel = null;
  16.  
  17. public static ConfigModel newInstance() throws Exception {
  18. return newInstance("mvc.xml");
  19. }
  20.  
  21. /**
  22. * 工厂模式创建config建模对象
  23. *
  24. * @param path
  25. * @return
  26. * @throws Exception
  27. */
  28. public static ConfigModel newInstance(String path) throws Exception {
  29. if (null != configModel) {
  30. return configModel;
  31. }
  32.  
  33. ConfigModel configModel = new ConfigModel();
  34. InputStream is = ConfigModelFactory.class.getResourceAsStream(path);
  35. SAXReader saxReader = new SAXReader();
  36. Document doc = saxReader.read(is);
  37. List<Element> actionEleList = doc.selectNodes("/config/action");
  38. ActionModel actionModel = null;
  39. ForwardModel forwardModel = null;
  40. for (Element actionEle : actionEleList) {
  41. actionModel = new ActionModel();
  42. actionModel.setPath(actionEle.attributeValue("path"));
  43. actionModel.setType(actionEle.attributeValue("type"));
  44. List<Element> forwordEleList = actionEle.selectNodes("forward");
  45. for (Element forwordEle : forwordEleList) {
  46. forwardModel = new ForwardModel();
  47. forwardModel.setName(forwordEle.attributeValue("name"));
  48. forwardModel.setPath(forwordEle.attributeValue("path"));
  49. forwardModel.setRedirect(forwordEle.attributeValue("redirect"));
  50. actionModel.put(forwardModel);
  51. }
  52.  
  53. configModel.put(actionModel);
  54. }
  55.  
  56. return configModel;
  57. }
  58.  
  59. public static void main(String[] args) {
  60. try {
  61. ConfigModel configModel = ConfigModelFactory.newInstance();
  62. ActionModel actionModel = configModel.get("/loginAction");
  63. ForwardModel forwardModel = actionModel.get("failed");
  64. System.out.println(actionModel.getType());
  65. System.out.println(forwardModel.getPath());
  66. } catch (Exception e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. }

3、创建中央控制器

DispatcherServlet

  1. package com.yuan.framework;
  2.  
  3. import java.io.IOException;
  4. import java.lang.reflect.Field;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.Set;
  10.  
  11. import javax.management.RuntimeErrorException;
  12. import javax.servlet.ServletException;
  13. import javax.servlet.http.HttpServlet;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16.  
  17. import org.apache.commons.beanutils.BeanUtils;
  18.  
  19. import com.yuan.web.AddCalAction;
  20. import com.yuan.web.DelCalAction;
  21.  
  22. /**
  23. * 中央控制器
  24. * 作用: 接受请求,通过请求寻找处理请求对应的子控制器。
  25. * @author ***
  26. *
  27. */
  28. public class DispatcherServlet extends HttpServlet {
  29.  
  30. /**
  31. *
  32. */
  33. private static final long serialVersionUID = 1L;
  34. // private Map<String , IAction> actionMap = new HashMap<>();
  35. //在configModel对象中包含了所有的子控制器信息,
  36. private ConfigModel configModel;
  37.  
  38. public void init() {
  39. // actionMap.put("/addCal", new AddCalAction());
  40. // actionMap.put("/delCal", new DelCalAction());
  41. try {
  42. String xmlPath = this.getInitParameter("xmlPath");
  43. if(xmlPath == null || "".equals(xmlPath)){
  44. configModel = ConfigModelFactory.newInstance();
  45. }
  46. else {
  47. configModel = ConfigModelFactory.newInstance(xmlPath);
  48. }
  49. } catch (Exception e) {
  50. // TODO Auto-generated catch block
  51. e.printStackTrace();
  52. }
  53. }
  54.  
  55. @Override
  56. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  57. doPost(req, resp);
  58.  
  59. }
  60.  
  61. @Override
  62. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  63. init();
  64. String url= req.getRequestURI();
  65. // /项目名/addCal.action
  66. url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
  67. // IAction action = actionMap.get(url);
  68. ActionModel actionModel = configModel.get(url);
  69. if(actionModel == null) {
  70. throw new RuntimeException("你没有配置action标签,找不到对应的子控制器来处理浏览器发送的请求");
  71.  
  72. }
  73.  
  74. try {
  75.  
  76. IAction action = (IAction) Class.forName(actionModel.getType()).newInstance();
  77.  
  78. //此时的action就是com.yuan.web.CalAction
  79. if(action instanceof ModelDrivern) {
  80. ModelDrivern drivern = (ModelDrivern) action;
  81. //此时的model的所有属性值是null的
  82. Object model = drivern.getModel();
  83.  
  84. BeanUtils.populate(model, req.getParameterMap());
  85.  
  86. //我们可以将req.getParameterMap()的值通过反射的方式将其塞进model实例中 (源码)
  87. // Map<String, String[]> parameterMap = req.getParameterMap();
  88. // Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
  89. // Class<? extends Object> clz = model.getClass();
  90. // for (Entry<String, String[]> entry : entrySet) {
  91. // Field field = clz.getField(entry.getKey());
  92. // field.setAccessible(true);
  93. // field.set(model, entry.getValue());
  94. // }
  95.  
  96. }
  97.  
  98. String code = action.execute(req, resp);
  99. ForwardModel forwardModel = actionModel.get(code);
  100. if(forwardModel!=null) {
  101. String jspPath = forwardModel.getPath();
  102. if("false".equals(forwardModel.getRedirect())) {
  103. //做转发的处理
  104. req.getRequestDispatcher(jspPath).forward(req, resp);
  105. }else {
  106. resp.sendRedirect(req.getContextPath()+jspPath);
  107. }
  108. }
  109.  
  110. } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SecurityException | InvocationTargetException e) {
  111. // TODO Auto-generated catch block
  112. e.printStackTrace();
  113. }
  114. // action.execute(req, resp);
  115. }
  116.  
  117. }

web.xml配置

  1. <servlet>
  2. <servlet-name>dispatcherServlet</servlet-name>
  3. <servlet-class>com.yuan.framework.DispatcherServlet</servlet-class>
  4. <init-param>
  5. <param-name>xmlPath</param-name>
  6. <param-value>/mvc.xml</param-value>
  7. </init-param>
  8.  
  9. </servlet>
  10. <servlet-mapping>
  11. <servlet-name>dispatcherServlet</servlet-name>
  12. <url-pattern>*.action</url-pattern>
  13. </servlet-mapping>

4、一个增强版的子控制器(ActionSupport)实现简单的子控制器(IAction)

IAction(接口)

  1. package com.yuan.framework;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9. /**
  10. * 子控制器
  11. * 作用:用来直接处理浏览器发送过来的请求。
  12. * @author **
  13. *
  14. */
  15. public interface IAction {
  16.  
  17. String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
  18.  
  19. }

ActionSupport      通过结果码控制页面的跳转,减少了逻辑层中的页面跳转代码重复性

  1. package com.yuan.framework;
  2.  
  3. import java.io.IOException;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.lang.reflect.Method;
  6.  
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. /**
  12. * 增强版子控制器
  13. * 原来的子控制器只可以处理一个请求,
  14. * 有时候用户请求是多个,但是都是操作同一张表,那么原有的子控制器代码编写繁琐。
  15. * 增强版的作用就是将一组相关的操作放到一个IAction中(子控制器)。
  16. * @author **
  17. *
  18. */
  19. public class ActionSupport implements IAction {
  20.  
  21. @Override
  22. public final String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23. String methodName= req.getParameter("methodName");
  24. String code = null;
  25. //this在这里指的是CalAction它的一个类实例
  26. try {
  27. Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
  28. m.setAccessible(true);
  29. code = (String) m.invoke(this, req,resp);
  30. } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  31. e.printStackTrace();
  32. }
  33.  
  34. return code;
  35. }
  36.  
  37. }

5、业务逻辑层      将一组相关的操作放到一个Action中(反射调用方法)

CalAction

  1. package com.yuan.web;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9. import com.entity.Cal;
  10. import com.yuan.framework.ActionSupport;
  11. import com.yuan.framework.ModelDrivern;
  12.  
  13. public class CalAction extends ActionSupport implements ModelDrivern<Cal> {
  14.  
  15. private Cal cal = new Cal();
  16.  
  17. public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  18. // String num1 = req.getParameter("num1");
  19. // String num2 = req.getParameter("num2");
  20. // Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
  21. req.setAttribute("res", cal.getNum1()- cal.getNum2());
  22. // req.getRequestDispatcher("res.jsp").forward(req, resp);
  23. return "res";
  24. }
  25.  
  26. public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  27. // String num1 = req.getParameter("num1");
  28. // String num2 = req.getParameter("num2");
  29. // Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
  30. req.setAttribute("res", cal.getNum1()+cal.getNum2());
  31. // req.getRequestDispatcher("res.jsp").forward(req, resp);
  32.  
  33. return "res";
  34. }
  35.  
  36. public String chen(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  37. // String num1 = req.getParameter("num1");
  38. // String num2 = req.getParameter("num2");
  39. // Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
  40. req.setAttribute("res", cal.getNum1()*cal.getNum2());
  41. // req.getRequestDispatcher("res.jsp").forward(req, resp);
  42.  
  43. return "res";
  44. }
  45.  
  46. public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  47. // String num1 = req.getParameter("num1");
  48. // String num2 = req.getParameter("num2");
  49. // Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
  50. req.setAttribute("res", cal.getNum1()/cal.getNum2());
  51. // req.getRequestDispatcher("res.jsp").forward(req, resp);
  52.  
  53. return "res";
  54. }
  55.  
  56. @Override
  57. public Cal getModel() {
  58.  
  59. return cal;
  60. }
  61.  
  62. }

6、创建一个模型接口       利用ModelDriver接口对Java对象进行赋值(反射读写属性),剪掉了逻辑层的获取jsp页面传值的代码重复性

  1. package com.yuan.framework;
  2.  
  3. /**
  4. * 模型驱动接口
  5. * 作用:将jsp页面所有传递过来的参数以及参数值
  6. * 都自动封装到浏览器所要操作的实体类中,
  7. * @author **
  8. *
  9. */
  10. public interface ModelDrivern<T> {
  11.  
  12. T getModel();
  13.  
  14. }

7、Cal 实体类

  1. package com.entity;
  2.  
  3. public class Cal {
  4.  
  5. private int num1;
  6. private int num2;
  7. public int getNum1() {
  8. return num1;
  9. }
  10. public void setNum1(int num1) {
  11. this.num1 = num1;
  12. }
  13. public int getNum2() {
  14. return num2;
  15. }
  16. public void setNum2(int num2) {
  17. this.num2 = num2;
  18. }
  19. public Cal(int num1, int num2) {
  20. super();
  21. this.num1 = num1;
  22. this.num2 = num2;
  23. }
  24. public Cal() {
  25. super();
  26. // TODO Auto-generated constructor stub
  27. }
  28.  
  29. }

8、jsp页面代码

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. <script type="text/javascript">
  9. function doSub(num){
  10. if(num==1){
  11. calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=add";
  12. }else if(num==2){
  13. calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=del";
  14. }
  15. else if(num==3){
  16. calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=chen";
  17. }
  18. else if(num==4){
  19. calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=chu";
  20. }
  21. calForm.submit();
  22. }
  23. </script>
  24. </head>
  25. <body>
  26. <form name="calForm" action="" method="post">
  27. num1:<input type="text" name="num1"> <br>
  28. num2:<input type="text" name="num2"> <br>
  29. <button onclick="doSub(1)">+</button>
  30. <button onclick="doSub(2)">-</button>
  31. <button onclick="doSub(3)">*</button>
  32. <button onclick="doSub(4)">/</button>
  33.  
  34. </form>
  35.  
  36. </body>
  37. </html>

9、运行结果:

谢谢观看^-^     !!!

自定义简单算法MVC框架的更多相关文章

  1. PHP之简单实现MVC框架

    PHP之简单实现MVC框架   1.概述 MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种 ...

  2. AsMVC:一个简单的MVC框架的Java实现

    当初看了<从零开始写一个Java Web框架>,也跟着写了一遍,但当时学艺不精,真正进脑子里的并不是很多,作者将依赖注入框架和MVC框架写在一起也给我造成了不小的困扰.最近刚好看了一遍sp ...

  3. 自己动手写一个简单的MVC框架(第一版)

    一.MVC概念回顾 路由(Route).控制器(Controller).行为(Action).模型(Model).视图(View) 用一句简单地话来描述以上关键点: 路由(Route)就相当于一个公司 ...

  4. 自己动手写一个简单的MVC框架(第二版)

    一.ASP.NET MVC核心机制回顾 在ASP.NET MVC中,最核心的当属“路由系统”,而路由系统的核心则源于一个强大的System.Web.Routing.dll组件. 在这个System.W ...

  5. php实现最简单的MVC框架实例教程

    本文以一个实例的形式讲述了PHP实现MVC框架的过程,比较浅显易懂.现分享给大家供大家参考之用.具体分析如下: 首先,在学习一个框架之前,基本上我们都需要知道什么是mvc,即model-view-co ...

  6. 封装简单的mvc框架

    MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式. MVC把软件系统分为三个基本部分:模型(Model).视图(View)和控制器(Controller). PH ...

  7. 一个简单的MVC框架的实现-基于注解的实现

    1.@Action注解声明 package com.togogo.webtoservice.annotations; import java.lang.annotation.Documented; i ...

  8. 一个简单的MVC框架的实现

    1.Action接口 package com.togogo.webtoservice; import javax.servlet.http.HttpServletRequest; import jav ...

  9. PHP写一个最简单的MVC框架

    照网上看的.Framework.class.php文件是灵魂. <?php class Framework { public static function run() { //echo &qu ...

随机推荐

  1. [WCF] - 使用 [DataMember] 标记的数据契约需要声明 Set 方法

    WCF 数据结构中返回的只读属性 TotalCount 也需要声明 Set 方法. [DataContract]public class BookShelfDataModel{    public B ...

  2. java实现根据特定密钥对字符串进行加解密功能

    在项目中我们经常遇到这样的场景,我们避免重要资源泄露需要将一些信息按照特定的方式(密钥)进行加密保存,然后在使用的时候再按照特定的方式(密钥)进行解密读取,以保证信息的相对安全.那么如何对信息进行加解 ...

  3. Python列表生成式测试

    print('*'*50) list1 = list(range(1,6)) print(list1) del(list1) #range(1,20) 按顺序生成列表 list1 = [] for x ...

  4. 以php中的比较运算符操作整型,浮点型,字符串型,布尔型和空类型

    字符,数字,特殊符号的比较依赖ASC II表,本表原先有127个,后来又扩充了一些,里面包含了奇奇奇怪的符号. ASC II表 https://baike.baidu.com/item/ASCII/3 ...

  5. K number(思维和后缀以及3的特性)(2019牛客暑期多校训练营(第四场))

    示例1: 输入:600 输出:4 说明:'600', '0', '0', '00' are multiples of 300. (Note that '0' are counted twice bec ...

  6. C#7 进入快速迭代道路

    out变量 有一定C#编程经历的园友一定没少写如下这样的代码: int speed; if (int.TryParse(speedStr, out speed)) speed*=; 注释:int.Tr ...

  7. elk 流程图

    ELK流程图 单纯使用ElK实现分布式日志收集缺点: 1.logstash太多了,扩展不好. 2.读取IO文件,可能会产生日志丢失 3.不是实时性 这时候就需要引入 kafka. kafka基于主题模 ...

  8. Yii2 redis 使用

    首先要安装一下redis的扩展 composer require yiisoft/yii2-redis 在配置文件中添加redis配置 'components' => [ .... 'redis ...

  9. springMVC关于异常优先级的处理

    优先级 既然在SpringMVC中有两种处理异常的方式,那么就存在一个优先级的问题: 当发生异常的时候,SpringMVC会如下处理: (1)SpringMVC会先从配置文件找异常解析器Handler ...

  10. js实现CheckBox全选或者不全选

    <html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">< ...