Custom simple algorithm MVC framework

 What is the MVC framework

   MVC full name Model View Controller, the model (model) - view (view) - Abbreviation controller (Controller), and
   it is a software design model, with a service logic, data, isolated tissue interface display method Code , its advantage is to gather business logic to a component which does not need to re-write the business logic and specified in improving personalized page at the same time, MVC is unique developed for mapping the traditional input, processing, display in a business logic graphical interface business.

  

  The core idea: carry out their duties

  Note 1: You can not cross-layer calls
  Note 2: You can only call top-down appearance

 

MVC Working Principle:

The main control (the ActionServlet) dynamic call sub-controllers (Action) to accomplish specific business logic invocation (trains, the console, the rail) request, the main controller, the sub-controller

 

Specific code as follows:

1, need to import jar kits

 

2, mvc.xml modeling information to the XML Configuration Action (reflection instantiated)

     Resolved to change in the framework of the code in order to complete customer demand, change the code in the frame is unreasonable

mvc.xml file

<?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>

</config>

ForwardModel

package com.yuan.framework;

import java.io.Serializable;

/**
 * 用来描述forward标签
 * @author Administrator
 *
 */
public class ForwardModel implements Serializable {

    private static final long serialVersionUID = -8587690587750366756L;

    private String name;
    private String path;
    private String redirect;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getRedirect() {
        return redirect;
    }

    public void setRedirect(String redirect) {
        this.redirect = redirect;
    }

}

ActionModel

package com.yuan.framework;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 用来描述action标签
 * @author Administrator
 *
 */
public class ActionModel implements Serializable{

    private static final long serialVersionUID = 6145949994701469663L;
    
    private Map<String, ForwardModel> forwardModels = new HashMap<String, ForwardModel>();
    
    private String path;
    
    private String type;
    
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void put(ForwardModel forwardModel){
        forwardModels.put(forwardModel.getName(), forwardModel);
    }
    
    public ForwardModel get(String name){
        return forwardModels.get(name);
    }
    
}

ConfigModel

package com.yuan.framework;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 用来描述config标签
 * @author Administrator
 *
 */
public class ConfigModel implements Serializable{

    private static final long serialVersionUID = -2334963138078250952L;
    
    private Map<String, ActionModel> actionModels = new HashMap<String, ActionModel>();
    
    public void put(ActionModel actionModel){
        actionModels.put(actionModel.getPath(), actionModel);
    }
    
    public ActionModel get(String name){
        return actionModels.get(name);
    }
    
}

ConfigModelFactory

package com.yuan.framework;

import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ConfigModelFactory {
    private ConfigModelFactory() {

    }

    private static ConfigModel configModel = null;

    public static ConfigModel newInstance() throws Exception {
        return newInstance("mvc.xml");
    }

    /**
     * 工厂模式创建config建模对象
     * 
     * @param path
     * @return
     * @throws Exception
     */
    public static ConfigModel newInstance(String path) throws Exception {
        if (null != configModel) {
            return configModel;
        }

        ConfigModel configModel = new ConfigModel();
        InputStream is = ConfigModelFactory.class.getResourceAsStream(path);
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(is);
        List<Element> actionEleList = doc.selectNodes("/config/action");
        ActionModel actionModel = null;
        ForwardModel forwardModel = null;
        for (Element actionEle : actionEleList) {
             actionModel = new ActionModel();
            actionModel.setPath(actionEle.attributeValue("path"));
            actionModel.setType(actionEle.attributeValue("type"));
            List<Element> forwordEleList = actionEle.selectNodes("forward");
            for (Element forwordEle : forwordEleList) {
                forwardModel = new ForwardModel();
                forwardModel.setName(forwordEle.attributeValue("name"));
                forwardModel.setPath(forwordEle.attributeValue("path"));
                forwardModel.setRedirect(forwordEle.attributeValue("redirect"));
                actionModel.put(forwardModel);
            }

            configModel.put(actionModel);
        }

        return configModel;
    }
    
    public static void main(String[] args) {
        try {
            ConfigModel configModel = ConfigModelFactory.newInstance();
            ActionModel actionModel = configModel.get("/loginAction");
            ForwardModel forwardModel = actionModel.get("failed");
            System.out.println(actionModel.getType());
            System.out.println(forwardModel.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Create a central controller

DispatcherServlet

package com.yuan.framework;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.management.RuntimeErrorException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

importorg.apache.commons.beanutils.BeanUtils; 

Import com.yuan.web.AddCalAction;
 Import com.yuan.web.DelCalAction; 

/ ** 
 * central controller 
 * role: receiving a request, by looking for the sub-control request process corresponding to the request device. 
 * @Author *** 
 * 
 * / 
public  class the DispatcherServlet the extends the HttpServlet { 

    / ** 
     * 
     * / 
    Private  static  Final  Long serialVersionUID = 1L ;
 //     Private the Map <String, the IAction> = new new ActionMap the HashMap <> ();
     // in configModel object contains all the information of the sub-controllers, 
    Private configModel configModel;
    
    public void init() {
//        actionMap.put("/addCal", new AddCalAction());
//        actionMap.put("/delCal", new DelCalAction());
        try {
            String xmlPath = this.getInitParameter("xmlPath");
            if(xmlPath == null || "".equals(xmlPath)){
                configModel  = ConfigModelFactory.newInstance();
            }
            else {
                configModel  = ConfigModelFactory.newInstance(xmlPath);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
        
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        init();
        String url= req.getRequestURI();
//        /项目名/addCal.action
        = url.substring URL (url.lastIndexOf ( "/"), url.lastIndexOf ( "." ));
 //         the IAction Action = actionMap.get (URL); 
        ActionModel actionModel = configModel.get (URL);
         IF (actionModel == null ) {
             the throw  new new a RuntimeException ( "you do not configure the action tag, find the corresponding sub-controller to process the requests sent from the browser" ); 
            
        } 
        
        the try { 
            
            the IAction action = (the IAction) the Class.forName (actionModel.getType . ()) the newInstance (); 
            
            // this case, action is com.yuan.web.CalAction 
            IF (action the instanceof ModelDrivern) { 
                ModelDrivern drivern= (ModelDrivern) Action;
                 // At this point all the attribute values of the model is null 
                Object model = drivern.getModel (); 
                
                BeanUtils.populate (model, req.getParameterMap ()); 
            
                // we can req.getParameterMap ( ) value thereof by a reflection of the way into the model instances (source)
 //                 the Map <String, String []> = req.getParameterMap the parameterMap ();
 //                 the Set <the Entry <String, String [] = the entrySet >> parameterMap.entrySet ();
 //                 Class model.getClass CLZ = (); <the extends Object?>
 //                 for (the entry <String, String []> entry: the entrySet) {
 //                     Field, Field = clz.getField (entry. getKey ());
 //                    field.setAccessible(true);
//                    field.set(model, entry.getValue());
//                }

            }
            
            String code = action.execute(req, resp);
            ForwardModel forwardModel = actionModel.get(code);
            if(forwardModel!=null) {
                String jspPath = forwardModel.getPath();
                if("false".equals(forwardModel.getRedirect())) {
                    //做转发的处理
                    req.getRequestDispatcher(jspPath).forward(req, resp);
                }else {
                    resp.sendRedirect(req.getContextPath()+jspPath);
                }
            }
            
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SecurityException | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//        action.execute(req, resp);
    }
    
}

web.xml Configuration

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>com.yuan.framework.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>xmlPath</param-name>
      <param-value>/mvc.xml</param-value>
    </init-param>
    
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

4, an enhanced version of the sub-controller (ActionSupport) to achieve a simple sub-controller (IAction)

IAction (Interface)

Package com.yuan.framework; 

Import java.io.IOException; 

Import javax.servlet.ServletException;
 Import the javax.servlet.http.HttpServletRequest;
 Import javax.servlet.http.HttpServletResponse; 

/ ** 
 * sub-controller 
 * Purpose: to deal directly request the browser sends over. 
 * @Author ** 
 * 
 * / 
public  interface the IAction { 
    
 String Execute (the HttpServletRequest REQ, the HttpServletResponse RESP) throws ServletException, IOException; 
 
 
}

ActionSupport       jump through the control result code page, the page jump codes reduces repetitive logic layer

Package com.yuan.framework; 

Import java.io.IOException;
 Import java.lang.reflect.InvocationTargetException;
 Import the java.lang.reflect.Method; 

Import javax.servlet.ServletException;
 Import the javax.servlet.http.HttpServletRequest;
 Import the javax .servlet.http.HttpServletResponse; 

/ ** 
 * enhanced version of the sub-controller 
 * original sub-controllers can only handle one request, 
 * sometimes multiple user requests, but all operate the same table, then the original sub controller code to write cumbersome. 
 * Edition enhancement is a set of related operations in IAction into a (sub-controller). 
 * @Author ** 
 * 
 * / 
public  class ActionSupport the implements the IAction { 

    @Override
    public final String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName= req.getParameter("methodName");
        String code = null;
        //this在这里指的是CalAction它的一个类实例
        try {
            Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            m.setAccessible(true);
            code = (String) m.invoke(this, req,resp);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
        
        
        return code;   
} }

5, the business logic into a set of related operations in an Action (reflection method call)

CalAction

package com.yuan.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entity.Cal;
import com.yuan.framework.ActionSupport;
import com.yuan.framework.ModelDrivern;

public class CalAction extends ActionSupport implements ModelDrivern<Cal> {

    private Cal cal = new Cal();
    
    public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String num1 = req.getParameter("num1");
//        String num2 = req.getParameter("num2");
//        Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
        req.setAttribute("res", cal.getNum1()- cal.getNum2());
//        req.getRequestDispatcher("res.jsp").forward(req, resp);            
        return "res";
    }
    
    
    public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String num1 = req.getParameter("num1");
//        String num2 = req.getParameter("num2");
//        Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
        req.setAttribute("res", cal.getNum1()+cal.getNum2());
//        req.getRequestDispatcher("res.jsp").forward(req, resp);
        
        return "res";
    }
    
    public String chen(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String num1 = req.getParameter("num1");
//        String num2 = req.getParameter("num2");
//        Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
        req.setAttribute("res", cal.getNum1()*cal.getNum2());
//        req.getRequestDispatcher("res.jsp").forward(req, resp);
        
        return "res";
    }
    
    
    public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String num1 = req.getParameter("num1");
//        String num2 = req.getParameter("num2");
//        Cal cal = new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
        req.setAttribute("res", cal.getNum1()/cal.getNum2());
//        req.getRequestDispatcher("res.jsp").forward(req, resp);
        
        return "res";
    }


    @Override
    public Cal getModel() {
        
        return cal;
    }
    
    
}

6, to create a model of an interface using Java objects ModelDriver interface assignment (reflected read-write property), cut repetitive code acquisition logic value jsp pages pass layer

Package com.yuan.framework; 


/ ** 
 * model-driven interfaces 
 * Function: The jsp pages transmission over all parameters and parameter values 
 * automatically encapsulated entity class browser to operate in, 
 * @author ** 
 * 
 * / 
public  interface ModelDrivern <T> { 

    T getModel (); 
    
}

7, Cal entity class

package com.entity;

public class Cal {

    private int num1;
    private int num2;
    public int getNum1() {
        return num1;
    }
    public void setNum1(int num1) {
        this.num1 = num1;
    }
    public int getNum2() {
        return num2;
    }
    public void setNum2(int num2) {
        this.num2 = num2;
    }
    public Cal(int num1, int num2) {
        super();
        this.num1 = num1;
        this.num2 = num2;
    }
    public Cal() {
        super();
        // TODO Auto-generated constructor stub
    }
 
}

8, jsp page code

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
  function doSub(num){
      if(num==1){
          calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=add";
      }else if(num==2){
          calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=del";
      }
      else if(num==3){
          calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=chen";
      }
      else if(num==4){
          calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=chu";
      }
      calForm.submit();
  }
</script>
</head>
<body>
<form name="calForm" action="" method="post">
num1:<input type="text" name="num1"> <br>
num2:<input type="text" name="num2"> <br>
    <button onclick="doSub(1)">+</button>
    <button onclick="doSub(2)">-</button>
    <button onclick="doSub(3)">*</button>
    <button onclick="doSub(4)">/</button>

</form>

</body>
</html>

9, the results:

plus

Less

Multiply

except

 

 

Thank you for watching ^ - ^! ! !

 

Guess you like

Origin www.cnblogs.com/ly-0919/p/11090884.html