What is the “MVC”?

  • MVC is a shorthand for Model, View and Controller. It is a specification for software design.

  • Is a way to organize code by separating business logic, data, and presentation

  • MVC’s main purpose is to reduce the bidirectional coupling between views and business logic

  • It is not a design pattern, but an architectural pattern (of course, there are differences between MVCS).

    Model: Data Model that provides the data to be presented and therefore contains both data and behavior. You can think of them as components of a domain model or A JavaBean (containing data and behavior), but these days they are generally separated: a Value Object (data Dao) and a Service layer (behavior Service). That is, the model provides model data query and model data status update functions, including data and business. View: Is responsible for presenting the model, which is generally the user interface we see, what the customer wants to see. Controller (Controller) : Receives user requests, delegates them to the model for processing (state changes), and returns the returned model data to the view for display. So the controller is doing the job of scheduling the circle and crossing it out just so you know

SpringMVC has many advantages: lightweight, easy to learn, simple junit testing, Restful style support, good compatibility with Spring, seamless integration….. Of course, the most important is to use more people more.

Common server-side MVC frameworks include: Struts, SpringMVC, ASP.NET MVC, Zend Framework, JSF; Common front-end MVC frameworks include Vue, Angularjs, React, and Backbone. MVC also evolved another design pattern such as MVP, MVVM, and so on…..

What does an MVC framework do

  1. A method that maps a URL to a Java class or Java class.
  2. Encapsulate user-submitted data.
  3. Process the request —- invoke the associated business process —- encapsulate the response data.
  4. Render the data of the response data. JSP/HTML and other presentation data.

Central controller

Spring’s Web framework is designed around DispatcherServlet. The purpose of the DispatcherServlet is to distribute requests to different processors. Starting with Spring2.5, annotation-based Controller declarations are available for Java 5 or higher users.

The SpringMVC framework, like many MVC frameworks,Request-driven Servlet dispatches requests and provides other functions around a central Servlet. DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class).

Implement an MVC operation using the original method

First you need to write a Dispatcher Servlet in web.xml


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

<! Write a DispatcherServlet, which is the heart of SpringMVC: also called request dispatcher or front-end controller
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <! -- Bind Spring(MVC) configuration file -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:xxxxx</param-value>
        </init-param>
        <! -- Set boot level to 1-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <! <url-pattern>/</url-pattern> </url-pattern> </url-pattern> </url-pattern>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
Copy the code

You can see from the code that you need to bind oneConfiguration file for Spring(MVC)“, then we write a configuration file in the resource directory to bind it


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

    <! -- Configure mapper -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <! Configure the adapter -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <! -- View resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <! -- prefix -- -- >
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <! - the suffix - >
        <property name="suffix" value=".jsp"/>
        
    </bean>
    <bean id="/hello" class="com.molu.controller.HelloController"/>

</beans>
Copy the code

We need to write a mapper, an adapter, and a view parser in the Spring configuration file (we don’t need to explicitly write the mapper and adapter in actual development)

Then we need to write a Controller class that the adapter can find

Once you’ve created the Controller class, you need to have that class inherit the Controller interface,Classes that implement this interface acquire controller functionality(The controller handles the request and returns the ModelAndView)

The important thing here is that you don’t inherit the Controller annotations (i.e., the second one)

After implementing the Controller interface, I need to rewrite his methods,Overriding this method simply returns a ModelAndViewCan beAfter implementing the interface and rewriting its methods, we write our own specific business code and view jumps in the methodThe test passed in the view jump here is the JSP I wrote earlierSo once we’re done with the view jump we’re done with the Controller class,The returned ModelAndView gives the view name to the view parser to concatenate

  <! -- View resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <! -- prefix -- -- >
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <! - the suffix - >
        <property name="suffix" value=".jsp"/>
Copy the code

After stitching and data filling, the data will be handed overDispatcher Servlet, by Dispatcher ServletGive the data to the user.So that’s the end of the original MVC implementation method, which has onedefectsOnly one method can be written to a controller. Should we write dozens or hundreds of classes if our website has dozens or hundreds of interfaces? withannotationsThere’s no confusion about that.

Annotations implement MVC operations

Annotations are a very convenient way to implement MVC. Ninety percent of real development uses annotations, and very few use the original approach.

1. To avoid Maven static resource filtering, we add the following code to POM.xml.

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
Copy the code

2. Next we write a DispatcherServlet in web.xml (same method as above).

    <! -- This is dead code, just change servlet-name -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <! -- Bind spring(MVC) configuration file -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.xml</param-value>
        </init-param>
        <! -- Set the boot level -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <! -- servlet-name = '/' -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
Copy the code

3. Bind the Spring (MVC) configuration file


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvn="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <! -- Automatically scan packets to validate annotations under specified packets, managed by IOC containers -->
    <context:component-scan base-package="com.molu.controller"/>

    <! Let SpringMVC not handle static resources -->
    <mvn:default-servlet-handler/>

    <! - support the MVC annotation driven @ RequestMapping commonly used in spring annotations to complete the mapping relationship To make the @ RequestMapping annotations to take effect Must be registered DefaultAnnotationHandlerMapping with the context And a AnnotationMethodHandlerAdapter instance this two instances in class level and treatment level. The annotation-driven configuration helps us to automatically inject the above two instances -->
    <mvn:annotation-driven/>
    <! -- View resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <! -- prefix -- -- >
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <! - the suffix - >
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>
Copy the code

4. Finally, write our Controller class and use the corresponding annotations in the class

package com.molu.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller // The @Controller annotation is used here to enable Spring to scan this class
public class HelloController {

    @RequestMapping("hello") / / url
    public String hello(Model model){
        // Use Model to encapsulate data (here is a simplified version of ModelAndView, usually used more)
        model.addAttribute("msg"."Hello,Molu");
        return "hello"; // The returned value is processed by the view parser}}Copy the code

The @Controller annotation is used to declare an instance of a Spring class. A class declared with @Controller is a Controller and will be hosted by Spring. All methods of the class in this annotation will be parsed by the view parser if the return value is String and there are concrete pages to jump to.

RequestMapping (@requestMapping) {RequestMapping (@requestMapping) {RequestMapping (@requestMapping) {RequestMapping (@requestMapping) {RequestMapping (@requestMapping) {RequestMapping (@requestMapping); The url of the parent relationship (that is, the value of @requestMapping on the class) needs to be written before the URL of the RequestMapping on the method.

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

4.1 Use RequestMapping annotations on classes

The code below uses RequestMapping annotations on the class, so if you want to access the data encapsulated by Model in the Hello method, you must add a “hello” to the URL (i.eRequestMapping value of the class) -eg:localhost:8080/Hello/hello The above illustration is just for demonstration. The Request Mapping annotation is not used on the class in this annotation operation

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 5. After that, we typed “localhost:8080/hello” in the browser to test, and the data we encapsulated with Model could be accessed in the figure.

You can see how easy it is to develop using annotations. The steps are as follows:

  1. Create a New Web project
  2. Import the relevant JAR package dependencies
  3. Write web.xml and write a Dispatcher Servlet
  4. Write a Spring (MVC) configuration file
  5. Create the corresponding control class (Controller)
  6. Improve the correspondence between the front view and controller
  7. Test run debugging

There are three things you must configure to use SpringMVC:

Processor mapper, processor adapter, view resolver

Generally, we only need to manually configure the view parser, while we only need to turn on the annotation driver for the processor mapper and processor adapter, which saves a large section of XML configuration and improves the development efficiency.