Custom MVC architecture [Part 1]

Table of contents

I. Introduction

1. What is the MVC architecture

2. The benefits of using the MVC architecture

3. The difference between MVC architecture and three-tier architecture

4. The idea of ​​MVC architecture

Two, custom MVC

1. Initial version

2. Advanced version

3. Reflection optimized version

4. Enhanced version of reflection


I. Introduction

1. What is the MVC architecture

The MVC architecture (Model-View-Controller), the Model-View-Controller architecture, is a common software design pattern for organizing and separating different components of an application.

  • Model (Model) : Represents the data and business logic in the application. The model is responsible for processing data reading and writing, verification, calculation and other operations, as well as processing business logic related to data. Models usually do not interact directly with the user interface, but instead go through controllers to fetch and update data.

  • View (View) : represents the user interface in the application. Views are responsible for presenting data to the user and receiving user input. Views usually do not contain any business logic, but are updated and retrieved by controllers. A model can have multiple views, and the views can be displayed in different forms, such as web pages, mobile application interfaces, etc.

  • Controller (Controller) : Responsible for handling user input, controlling the flow of the application, and coordinating the interaction between the model and the view. Controllers receive user input and update models and views accordingly. It converts the user's operation into a request for the model or an update for the view, so as to realize the interaction between data and interface.

2. The benefits of using the MVC architecture

The advantage of the MVC architecture is that it can achieve good code reuse, scalability, maintainability and testability. By separating the different responsibilities of the application, each component changes independently, reducing the degree of coupling, and also enabling the development team to better collaborate and manage projects.

Life case:

If there is a restaurant, there is only one owner. Purchasing, serving customers, cooking, serving, and checking out are all done by the boss. Isn’t it time-consuming and laborious? If he recruits people to do these things for him, will it save a lot of time, and we have one thing for one People, if there is a problem in a certain link, it can be directly connected.

Project cases:

The restaurant is our project, the jsp page is the boss, and he does everything. The amount of code is very large and it is not conducive to maintenance. At this time, we need to carry out "classification management" to turn our code into an MVC architecture. MVC is Model (model) - view (view) - controller (controller). They each handle their own tasks, high cohesion and low coupling, improving the efficiency of our code writing and post-maintenance.

3. The difference between MVC architecture and three-tier architecture

1. The three-tier architecture is based on business logic, while MVC is based on pages;

2. The three-tier is a kind of software architecture, which realizes programming through the interface. The MVC mode is a composite design mode and a solution;

3. The three-tier architecture pattern is an architectural pattern, and MVC is a design pattern;

4. The three-tier architecture pattern can be attributed to the deployment pattern, and MVC can be attributed to the presentation pattern.

Note : The MVC architecture and the three-tier architecture are not mutually exclusive, and can be combined and adjusted according to actual needs. For example, the MVC architecture can be used as a part of the presentation layer to manage the interaction of the user interface, and at the same time, a three-tier architecture is used to divide responsibilities in the business logic layer and data access layer.

4. The idea of ​​MVC architecture

 As shown in the figure, the view is responsible for displaying the data in the model to the user, and providing a user interface for interacting with the user, sending requests to the Servlet, which is the controller, and the controller controls the behavior of the application by receiving user input and then goes to At the back end, that is, the data access layer gets the corresponding data and updates the model and view according to the interaction.

Two, custom MVC

Version iteration: I will lead you step by step to evolve into the MVC architecture we use today, so that everyone can more intuitively feel why it is used and how it evolved.

1. Initial version

Version 1: One request parameter (operation) corresponds to one servlet

package com.xw.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 模拟版本一mvc新增操作
 */
@WebServlet("/BookAdd.do")
public class BookAddServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("我是版本一的mvc__新增操作。。。");
	}

}

Disadvantages: The above servlets need to be written multiple times, and one servlet must be written for one operation, which is very cumbersome and not conducive to maintenance.

2. Advanced version

Version 2: Addition, deletion, modification and query are all a Servlet, and the if operation judgment is performed in the Servlet
package com.xw.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 模拟版本二mvc增删改查共用一个Servlet操作
 */
@WebServlet("/BookCRUD.do")
public class BookCRUDServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收请求参数
		String parameter = request.getParameter("CrudName");
		//判断前端传递过来的是什么参数
		if(parameter.equals("add")) {
			add(request,response);
		}else if(parameter.equals("upd")) {
			upd(request,response);
		}else if(parameter.equals("del")) {
			del(request,response);
		}else if(parameter.equals("list")) {
			list(request,response);
		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本二的查询");
		
	}

	private void del(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本二的删除");
		
	}

	private void upd(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本二的修改");
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本二的新增");
		
	}

}

Disadvantages: Although only one servlet needs to be written, an if conditional branch needs to be added every time an operation is added. If our operation requirements increase, the amount of code will be very redundant.

3. Reflection optimized version

Version 3: Reflection mechanism optimizes if conditional judgment

package com.xw.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 模拟版本三mvc增删改查反射机制优化if条件判断
 */
@WebServlet("/BookClass.do")
public class BookClassCRUDServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收请求参数
		String CrudName = request.getParameter("CrudName");
		
		try {
			//获取该servlet的所有方法
			Method m = this.getClass().getDeclaredMethod(CrudName, HttpServletRequest.class, HttpServletResponse.class);
			//打开访问权限
			m.setAccessible(true);
			//调用该类的方法
			m.invoke(this,request,response );
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
	}

	private void list(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本三反射机制优化的查询");
		
	}

	private void del(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本三反射机制优化的删除");
		
	}

	private void upd(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本三反射机制优化的修改");
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本三反射机制优化的新增");
		
	}

}

Disadvantages: Although only one servlet needs to be written, and there is no need to write if condition judgment, but in the project category, we not only have one book, but also Goods, Student, etc. also need to write multiple servlets, one servlet corresponds a table.

4. Enhanced version of reflection

Create the DispatchServlet central controller to receive the request and send the request to the corresponding sub-controller and complete the request path in the init method and the corresponding configuration of the sub-controller class and the request processing of the doPost method.

package com.xw.framework;

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

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 com.xw.servlet.BookAction;
import com.xw.servlet.GoodsAction;

/**
 * 中央控制器拦截请求根据请求找到子控制器
 */
@WebServlet("*.do")
public class DispatchServlet extends HttpServlet {
	//保存子控制器
	private Map<String, ActionSupport> actionMap = new HashMap<String, ActionSupport>();
	
	@Override
	public void init() throws ServletException {
		//初始化子控制值
		actionMap.put("/book", new BookAction());
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取到url请求
		 String url = request.getRequestURI();
		//截取指定需要操作的表
		url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
		//根据请求截取到key找到对应的子控制器
		ActionSupport actionSupport = actionMap.get(url);
		//调用子控制器处理业务逻辑
		actionSupport.execute(request, response);
	}

}

Create an Action abstract sub-controller and define the execute method to handle specific core business logic processing.

package com.xw.framework;

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

/**子控制器并定义execute方法,用于处理具体的核心业务逻辑处理
 * @author Java方文山
 *
 */
public interface Action {
		public String execute(HttpServletRequest req, HttpServletResponse resp);
}

Create ActionSupport and inherit the abstract class Action, rewrite the execute method, and find the Servlet sub-controller saved in the corresponding Map collection through reflection to implement business logic layer processing.

package com.xw.framework;

import java.lang.reflect.Method;

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


import com.sun.corba.se.spi.orbutil.fsm.FSM;
import com.sun.corba.se.spi.orbutil.fsm.Input;

/**重写execute方法,实现业务逻辑处理
 * @author Java方文山
 *
 */
public  class ActionSupport implements Action {

	public String execute(HttpServletRequest req, HttpServletResponse resp) {
		String invoke = null;
		try {
			//接收请求参数
			String CrudName = req.getParameter("CrudName");
			//获取该servlet的所有方法
			Method m = this.getClass().getDeclaredMethod(CrudName, HttpServletRequest.class, HttpServletResponse.class);
			//打开访问权限
			m.setAccessible(true);
			//调用该类的方法
			invoke = (String) m.invoke(this, req, resp);
			
		} catch (Exception e) {
			e.printStackTrace();
		
	}
		return invoke;

	}

}

Create BookAction to inherit ActionSuppor to realize business logic processing.

package com.xw.servlet;

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

import com.xw.framework.ActionSupport;


public class BookAction extends ActionSupport {
	private void list(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的查询——book");
		
	}

	private void del(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的删除——book");
		
	}

	private void upd(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的修改——book");
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的新增——book");
		
	}
	
}

Here we have completed our fourth-generation MVC architecture! !

When we need to operate another table, we only need to configure the sub-controller in the DispatchServlet central controller and finally write the business logic layer of the sub-controller.

For example :

I also need to add, delete, modify and query the Goods table

① Configure the sub-controller

 ② Write sub-controller

package com.xw.servlet;

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

import com.xw.framework.ActionSupport;


public class GoodsAction extends ActionSupport {
	private void list(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的查询——goods");
		
	}

	private void del(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的删除——goods");
		
	}

	private void upd(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的修改——goods");
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("我是版本四反射机制优化的新增——goods");
		
	}
	
}

Next, test and see the print results

 

Is it simpler than the previous three generations? After reading it, do you have a better understanding of the use of MVC?

So far, my first custom MVC is shared here! ! !

Guess you like

Origin blog.csdn.net/weixin_74318097/article/details/131463495