当前位置:网站首页>Custom MVC principle and framework implementation
Custom MVC principle and framework implementation
2022-07-29 02:16:00 【I don't want this brain anymore】
Catalog
2. Customize MVC Working principle diagram
3. Customize mvc Simple implementation of
4. Improve the central controller
1. Request distribution function
2. Use profile configuration action
3. Request parameter processing
1. What is? MVC
MVC The full name is Model View Controller, It's a model (model)- View (view)- controller (controller) Abbreviation . It's a software design paradigm .
Using a business logic 、 data 、 The interface displays the separated method organization code , Gather business logic into a component , While improving and personalizing the interface and user interaction , No need to rewrite business logic .
Improved program maintainability 、 Portability 、 Scalability and reusability , It reduces the difficulty of program development . It is mainly divided into models 、 View 、 Controller layer 3 .
- Model (model): It is the main part of the application , It mainly includes business logic module (web In the project dao class ) And data module (pojo class ).pojo Generally, it can be called entity domain model ,dao and service It is called process domain model .
- View (view): The interface with which the user interacts 、 stay web The middle view is generally composed of jsp,html form , Others include android,ios wait .
- controller (controller): Receive requests from the interface And give it to the model for processing In this process, the controller does not do any processing, but plays a connecting role .
What's not enough :
- Increase the complexity of system structure and implementation . For a simple interface , Strictly observe MVC, Need to make the model 、 View separate from controller , Increase system complexity
- The relationship between view and controller is too close
2. Customize MVC Working principle diagram
Core component description :
- The central controller (ActionServlet): Complex receive all requests , And give specific treatment to the controller .
- Self controller (Action): Responsible for processing requests allocated by the central processing unit
- View (view): jsp page , Responsible for the display
- Model (Model): Responsible for business processing logic
3. Customize mvc Simple implementation of
1. The central controller
adopt servlet To realize a central controller , Responsible for receiving all requests .( Subsequently, the central controller will forward the request to each sub controller , Here you can receive the request first , The forwarding function is followed by )
/**
* The central controller , Be responsible for receiving all requests and giving them to the controller for specific processing
* @author Administrator
*/
@WebServlet("*.action")
public class ActionDispatchServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
doPost(req, resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("dopost ..... ");
}
}2.Action Interface definition
Action The interface defines the behavior that each sub controller needs to follow , Make all sub controllers have the same abstract type , So we can use it in the central controller Action Interface type to reference all sub controllers . This provides conditions for users to extend customized sub controllers .
/**
* Each sub controller must implement this interface , Responsible for processing requests allocated by the central processing unit
* @author Administrator
*/
public interface Action {
/**
* Processing requests
* @param req request
* @param resp Respond to
* @return String Return forwarded or redirected jsp Page name
*/
String exeute(HttpServletRequest req, HttpServletResponse resp);
}3. Implement sub controllers
For the convenience of debugging , I have implemented two sub controllers here (= ̄ω ̄=)
public class BookAction implements Action {
@Override
public String getBooks(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("BookAction...");
return "books";
}
}public class StudentAction implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("StudentAction");
return "students";
}
4. Improve the central controller
For the sake of understanding , We can do it step by step , Gradually improve the central controller :
- Write a simple request distribution implementation function
- Realize the function of configuring the sub controller through the configuration file
- Improve the request parameter processing function
1. Request distribution function
@WebServlet("*.action")
public class ActionDispatchServlet extends HttpServlet{
// Used to hold path And action Mapping of sub controllers
public static Map<String, Action> actionMap = new HashMap<>();
static {
actionMap.put("/studentAction", new StudentAction());
actionMap.put("/bookAction", new BookAction());
}
@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 {
String spath = req.getServletPath();
String path = spath.split("\\.")[0];
Action action = getActionByPath(path);
String name = action.execute(req, resp);
System.out.println(name);
}
}2. Use profile configuration action
In the example above , Create directly in the central controller action Sub controller , If you add a new sub controller, you need to add , It's not practical . To increase flexibility , Can be action Transfer to the configuration file to configure , The central controller initializes through configuration action Sub controller .
(1) At this time, we need to config.xml File analysis and Modeling project Integrate the functions of .
(ConfigModel,ActionModel,ForwardModel,ConfigModelFactory)
(2) In the project src Add the following configuration files to the directory (config.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
<!ELEMENT config (action*)>
<!ELEMENT action (forward*)>
<!ELEMENT forward EMPTY>
<!ATTLIST action
path CDATA #REQUIRED
type CDATA #REQUIRED
>
<!ATTLIST forward
name CDATA #REQUIRED
path CDATA #REQUIRED
redirect (true|false) "false"
>
]>
<config>
<action path="/studentAction" type="com.zking.action.StudentAction">
<forward name="students" path="/students.jsp" redirect="false"/>
</action>
<action path="/bookAction" type="com.zking.action.BookAction">
<forward name="books" path="/books.jsp" redirect="false"/>
</action>
</config>(3) Improve the central processing unit , Get the sub controller configuration through the configuration file
@WebServlet("*.action")
public class ActionDispatchServlet extends HttpServlet{
private static ConfigModel configModel = ConfigModelFactory.getConfig();
@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 {
String spath = req.getServletPath();
String path = spath.split("\\.")[0];
Action action = getActionByPath(path);
// Request forwarding
String name = action.execute(req, resp);
ForwardModel forward = configModel.find(path).find(name);
if(forward.isRedirect()) {
resp.sendRedirect(req.getContextPath()+forward.getPath());
} else {
req.getRequestDispatcher(forward.getPath()).forward(req, resp);
}
}
/**
* adopt path obtain Action Example
* @param path
* @return
*/
private Action getActionByPath(String path) {
ActionModel am = configModel.find(path);
try {
Class<? extends Action> ac = (Class<? extends Action>)Class.forName(am.getType());
return ac.newInstance();
} catch (ClassNotFoundException
| InstantiationException
| IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}notes : In the implementation of this example Action The sub controller is in multi instance mode , And each request corresponds to one Action example
3. Request parameter processing
(1) Defining interfaces
/**
* For those that need to process request parameters Action You can get the request parameters by implementing this interface
* processing capacity , The central controller will use this interface to obtain Model object , And unified treatment
* Parameters
* @author Administrator
*/
public interface ModelDrive {
Object getModel();
}(2) Add the processing capacity of request parameters to the central processing unit
@WebServlet("*.action")
public class ActionDispatchServlet extends HttpServlet{
private static ConfigModel configModel = ConfigModelFactory.getConfig();
@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 {
String spath = req.getServletPath();
String path = spath.split("\\.")[0];
Action action = getActionByPath(path);
// Set query parameters
if(action instanceof ModelDrive) {
ModelDrive m = (ModelDrive)action;
Object bean = m.getModel();
try {
BeanUtils.populate(bean,req.getParameterMap());
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ActionDispatchSetParameterException(" An exception occurred while processing parameters in the central controller ");
}
}
// Request forwarding
String name = action.execute(req, resp);
ForwardModel forward = configModel.find(path).find(name);
if(forward.isRedirect()) {
resp.sendRedirect(req.getContextPath()+forward.getPath());
} else {
req.getRequestDispatcher(forward.getPath()).forward(req, resp);
}
}
/**
* adopt path obtain Action Example
* @param path
* @return
*/
private Action getActionByPath(String path) {
ActionModel am = configModel.find(path);
try {
Class<? extends Action> ac = (Class<? extends Action>)Class.forName(am.getType());
return ac.newInstance();
} catch (ClassNotFoundException
| InstantiationException
| IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}(3) Handle null And empty string conversion
Method 1 : Add null And empty string conversion code
@WebServlet("*.action")
public class ActionDispatchServlet extends HttpServlet{
private static ConfigModel .....
/**
* When Servlet Container start up Web Call this method when applying .
* After calling the method , The container is right again Filter initialization ,
* And for those in Web The application needs to be initialized when it starts Servlet To initialize .
*/
static {
ConvertUtils.register(new IntegerConverter(null), Integer.class);
ConvertUtils.register(new FloatConverter(null), Float.class);
ConvertUtils.register(new DoubleConverter(null), Double.class);
ConvertUtils.register(new LongConverter(null), Long.class);
ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
}
@Override
protected void doGet......
}
notes : The omitted code is written in the first few central controllers , I won't repeat it here .
Method 2 : Add a listener , Register the converter when the application starts .
/**
* ServletContextListener Interface for Servlet API The interface , For monitoring ServletContext Object lifecycle .
* When Servlet Container starts or terminates Web When applied , Will trigger ServletContextEvent event , The incident was caused by
* ServletContextListener To deal with it .
* @author Administrator
*/
@WebListener
public class BeanUtilsListener implements ServletContextListener{
/**
* When Servlet Container termination Web Call this method when applying . Before calling this method ,
* The container will destroy everything first Servlet and Filter filter .
*/
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
/**
* When Servlet Container start up Web Call this method when applying .
* After calling the method , The container is right again Filter initialization ,
* And for those in Web The application needs to be initialized when it starts Servlet To initialize .
*/
@Override
public void contextInitialized(ServletContextEvent arg0) {
ConvertUtils.register(new IntegerConverter(null), Integer.class);
ConvertUtils.register(new FloatConverter(null), Float.class);
ConvertUtils.register(new DoubleConverter(null), Double.class);
ConvertUtils.register(new LongConverter(null), Long.class);
ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
}
}4. perfect Action
Every Action There can only be one execute Method , If you deal with the addition, deletion, modification and query of a module, you need to write multiple Action, It will be more troublesome . If in a Action Multiple request methods can be processed in the instance , The framework will be more flexible .
- It is specified that the request parameter must contain a “methodName” Parameters , Used to specify the method of processing the request Action The method in
- Build an abstract class , Implementation of this class Action Sub controller interface , Call methods in its subclasses through the reflection mechanism , The method name has request parameters “methodName” Appoint .
- Need to develop Action Sub controller , Integrate the abstract classes built in the previous step , The method name written to process the request should be consistent with the request parameters “methodName” The specified method name matches , Simultaneous need HttpServletRequest and HttpServletResponse Two parameters ( This parameter is reserved mainly for the processing of requests )
(1) Build abstract classes
public abstract class AbstractAction implements Action{
// obtain methodName The specified method , Then call the method through the reflection mechanism
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
String methodName = req.getParameter("methodName");
Class<? extends Action> clazz = (Class<? extends Action>)this.getClass();
try {
Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
return (String)method.invoke(this, req,resp);
} catch (NoSuchMethodException
| SecurityException
| IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
(2) Self defined Action Example of sub controller
public class BookAction extends AbstractAction implements ModelDrive{
private Book book = new Book();
@Override
public Object getModel() {
return book;
}
public String getBooks(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("BookAction getBooks..."+book);
return "books";
}
}Be careful : You need to add a methodName Fixed parameters of , This parameter specifies the Action The name of the method in .
Example :http://localhost:8080/ Project name /bookAction.action?methodName=getBooks&id=1000
getBooks Is the method name of the sub controller
4. pack jar package
Will customize mvc Framing jar package , So that it can be used in other projects .
project --( Right click )-->Export

choice JAR file


This article ends here (づ ̄ 3 ̄)づ, Bye-bye .
边栏推荐
- iVX低代码平台系列详解 -- 概述篇(二)
- The growth path of embedded engineers
- 基于C51控制蜂鸣器
- Jetpack--了解ViewModel和LiveData的使用
- Comprehensive use method of C treeview control
- Try to understand the essence of low code platform design from another angle
- druid. io index_ Realtime real-time query
- Type analysis of demultiplexer (demultiplexer)
- Why can't Bi software do correlation analysis
- druid. IO custom real-time task scheduling policy
猜你喜欢

LeetCode 练习——剑指 Offer 45. 把数组排成最小的数

Type analysis of demultiplexer (demultiplexer)

Understand the working principle of timer in STM32 in simple terms
![What is a proxy server? [2022 guide]](/img/d8/f9ff56608ab42df9127493bc038961.png)
What is a proxy server? [2022 guide]

Rgbd point cloud down sampling

Mathematical modeling -- the laying of water pipes

2022年编程语言排名,官方数据来了,让人大开眼界

"Wei Lai Cup" 2022 Niuke summer multi school training camp 2, sign in question GJK

【云原生与5G】微服务加持5G核心网

Internet of things development -- mqtt message server emqx
随机推荐
Random talk on distributed development
Leetcode/0 and 1 consecutive subarrays with the same number
“蔚来杯“2022牛客暑期多校训练营3,签到题CAJHF
Control buzzer based on C51
(arxiv-2018) reexamine the time modeling of person Reid based on video
(cvpr-2019) selective kernel network
JetPack--Navigation实现页面跳转
Lm13 morphological quantification momentum period analysis
Related function records about string processing (long-term update)
Anti crawler mechanism solution: JS code generates random strings locally
物联网开发--MQTT消息服务器EMQX
在Qt中如何编写插件,加载插件和卸载插件
JVM memory overflow online analysis dump file and online analysis open.Hprof file to get JVM operation report how jvisualvm online analysis
Promise解决异步
数学建模——永冻土层上关于路基热传导问题
Mobile communication -- simulation model of error control system based on convolutional code
[MySQL] SQL aliases the table
什么是作用域和作用域链
12.< tag-动态规划和子序列, 子数组>lt.72. 编辑距离
[UE4] replay game playback for ue4.26