Introduction to MVC

  • MVC is a software design specification, short for Model, View, and Controller.
  • MVC is a common architectural pattern whose purpose is to decouple!
  • Model: The data model provides the data to be displayed on the page, also called the business logic layer. The model layer is a broad overview. The model layer includes the Service layer and the Dao layer.
  • View: Responsible for displaying the data model + view frame, which is the web page we see!
  • Controller: Receives user requests, delegates to the model for processing, and returns the returned model data to the view after processing, and the view is responsible for display.
  • Before the MVC architecture was proposed, the development of Web pages only had two layers: model and view; that is to say, there was no Controller control layer. Let’s take a look at why MVC will successfully replace the traditional two-tier architecture.

personally organize some information here, friends in need can click to receive it directly.

Basic knowledge of Java

22 Java architect core books

Java learning routes and materials from 0 to 1

1000+ channels 2021 latest

advantage:

The architecture is simple and easy to implement.

Disadvantages:

The responsibilities of the view layer are not single; not only need to encapsulate the data, but also need to write logical code to call the model layer. That is to say, the view layer here serves as the view + control two responsibilities; the view layer directly deals with the model layer and the confusion of the page , Not conducive to maintenance

The proposed MVC architecture is to separate the view and the model layer, and the two do not directly deal with each other; instead, they act as a bridge between the two through the control layer;

The view layer only needs to focus on data encapsulation and display

Model layer focuses on business logic

The control layer is responsible for processing the requests submitted by users and coordinating the view and model layers

SpringMVC execution process

The core of the SpringMVC framework revolves around the DispatcherServlet front controller. It is used to coordinate all Servlets to parse the user's request, find the corresponding Servlet for processing, and finally give a response! The DispatcherServlet function can be similar to the CPU processor, the human brain...

  • The user initiates a request through the view page or URL address path, and the front-end controls the DispatcherServlet to receive the user's request and start operation!
  • DispatcherServlet calls HandlerMapping to find the Handler that is ultimately used for execution
  • HandlerExecution includes specific executor Handler, HandlerInterceptor processor interceptor. Return it to the front controller DispatcherServlet.
  • Match the obtained HandlerExecution object to the corresponding processor adapter HandlerAdapter, and parse it.
  • The processor adapter HandlerAdapter finally successfully matched the Servlet class of the Controller layer written by the programmer.
  • The Controller layer has clear responsibilities, calls the model layer to access the database, and obtains the data and views that need to be responded to the user in the end.
  • In the Controller layer, data and views are encapsulated in ModelAndView objects, and then they are returned to the handler adapter HandlerAdapter.
  • The processor adapter HandlerAdapter receives the result returned by the Controller for processing, and then transfers it to the front controller DispatcherServlet.
  • The front controller DispatcherServlet calls the view resolver ViewResolver; ViewResolver parses the data in ModelAndView, parses the response view name, finds the corresponding view, and finally encapsulates the data into the view!
  • The view resolver ViewResolver returns the view name to the front controller DispatcherServlet, and finally the front controller DispatcherServlet calls the response view to show the user!

The first SpringMVC program

JSP page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

Write the corresponding Servlet (Controller)

public class HelloController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        // 1. 创建模型-视图
        ModelAndView mv = new ModelAndView();
        
        //调用业务层
        // 2. 封装数据对象
        mv.addObject("message","Hello, SpringMVC!");

        // 3. 封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hellomvc");
        return mv;
    }

}

Configure SpringMVC core file

In the core configuration file, configure the mapper, adapter, and resolver; finally, the requested path and the corresponding Servlet class are handed over to the IOC container for hosting.

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 1. 配置处理器映射器   -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <!-- 2. 配置处理器适配器  -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!-- 3. 配置视图解析器 -->
    <bean  id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/page/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 4. 将servlet交给IOC容器管理 -->
    <bean id="/hellomvc" class="com.controller.HelloController"/>
</beans>

Configure mapping path processing

Since all Sevlets do not follow their respective mapping paths, but are uniformly dispatched by the front controller DispatcherServlet, only DispatcherServlet needs to be configured in the web.xml of the project. Then hand the SpringMVC core configuration file to the front controller DispatcherServlet!

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
         
    <!--1.注册DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- 关联Spring的核心配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:SpringMVC-Servlet.xml</param-value>
        </init-param>
        <!-- 启动级别1 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Test Results

Analysis and summary

There is no need to configure the mapping path of a separate Servlet in web.xml, but DispatcherServlet directly. This is because the front controller will look up according to HandlerMapping by itself.

Servlet does not need to inherit the HttpServlet class, because DispatcherServlet inherits HttpServlet. And now the Servlet written to implement the Controller interface will be found through the adapter HandlerAdapter!

At last

You have all seen this, think the article is helpful to you, remember to give a thumbs up.


前程有光
936 声望618 粉丝