Detailed explanation of the working principle of spring MVC

Detailed explanation of the working principle of spring MVC

Before learning, let's take two pictures of Shentu Zhenlou

What is MVC

In the classic MVC mode, m refers to the business model, V refers to the user interface, and C is the controller. The purpose of using MVC is to realize M and V code Separation, so that the same program can use different expressions. Among them, the definition of View is relatively clear, that is, the user interface.

What is spring MVC

Spring MVC is a part of the Spring Framework and a lightweight Web framework based on Java to implement MVC.

Official documents: https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/web.html#spring-web

Features of Spring MVC:

Lightweight, easy to learn

Efficient, request response based MVC framework

Good compatibility with Spring and seamless combination

Convention over configuration

Powerful functions: RESTful, data validation, formatting, localization, theme, etc

Concise and flexible

Spring's web framework is designed around the dispatcher Servlet

Central controller

Spring MVC is designed around the core dispatcher servlet. Its function is to distribute different requests to different processors

Principle of spring MVC

When the customer initiates a request, the request is intercepted by the front controller, and the controller processes the request

The controller processes the request, creates a data model, accesses the database, and returns the model response to the central controller

The controller returns the response to the view and returns the view together to the customer

How Spring works

Dispatcher servlet represents the front controller and is the control center of the whole spring MVC. When the user sends a request, the dispatcher servlet receives the request and intercepts the request.
Suppose the url of the request is: http://localhost:8080/SpringMVC/hello
As above, the url is divided into three parts:
http://localhost:8080 Server domain name

Spring MVC is a web site deployed on the server

hello indicates the controller

Through analysis, the above url is expressed as: request the hello controller of the spring MVC site located on the server localhost:8080.

HandlerMapping is processor mapping. DispatcherServlet calls HandlerMapping, which looks up the Handler according to the request url

HandlerExecution refers to a specific Handler. Its main function is to find the controller according to the url. The controller found by the url above is: hello.

HandlerExecution passes the parsed information to DispatcherServlet, such as parsing controller mapping.

The HandlerAdapter represents a processor adapter that executes the Handler according to specific rules.

The Handler lets the specific Controller execute.

The Controller returns the specific execution information to the HandlerAdapter, such as ModelAndView.

The HandlerAdapter passes the logical name or model of the view to the dispatcher servlet.

DispatcherServlet calls the view resolver to resolve the logical view name passed by the HandlerAdapter.

The view parser passes the parsed logical view name to the dispatcher servlet.

DispatcherServlet calls a specific view according to the view result parsed by the view parser.

The final view is presented to the user.

How to use configuration implementation

After setting up the environment

1. Configure web XML file

  <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>//Here, select the file address of the spring MVC to be configured
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Here is to configure DispatcherServlet

2. Configure the spring MVC configuration file

<?xml version="1.0" encoding="UTF-8"?>
<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
       http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

Add process mapper object

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

Add processing adapter object

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

Add view adapter object

<!--view resolver :DispatcherServlet Give it to him ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
   <!--prefix-->
   <property name="prefix" value="/WEB-INF/jsp/"/>
   <!--suffix-->
   <property name="suffix" value=".jsp"/>
</bean>

Write operation business layer

public class HelloController implements Controller {

   public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
       //ModelAndView models and views
       ModelAndView mv = new ModelAndView();

       //Encapsulate the object and put it in ModelAndView. Model
       mv.addObject("msg","HelloSpringMVC!");
       //Encapsulate the view to jump to and put it in ModelAndView
       mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
       return mv;
  }
   
}

Note that the Controller interface needs to be implemented

To host this class to springzhong

<bean id="/hello" class="com.kuang.controller.HelloController"/>

Start tomcat and the configuration is successful

Pit description

When we start tomCat, we find that there is a 404 error, which may be that our jar package is not imported, so we can configure it according to the following operations

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-reahydn1-1625119382135) (C: \ users \ user \ appdata \ roaming \ typora \ typora user images \ image-20210701140004459. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-pxmugjjz-1625119382136) (C: \ users \ user \ appdata \ roaming \ typora \ typora user images \ image-20210701140030088. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ciu7nrji-1625119382137) (C: \ users \ user \ appdata \ roaming \ typora \ typora user images \ image-20210701140052620. PNG)]

Import the jar package into the lib directory

4 error, which may be that our jar package is not imported, so we can configure it according to the following operations

[external chain picture transferring... (IMG reahydn1-1625119382135)]

[external chain picture transferring... (IMG pxmugjjz-1625119382136)]

[external chain picture transferring... (img-ciU7nRJI-1625119382137)]

Import the jar package into the lib directory

Keywords: Spring MVC

Added by JJohnsenDK on Tue, 25 Jan 2022 15:31:04 +0200