“This is the 26th day of my participation in the August More Text Challenge.

Before learning about SpringMVC, let’s review MVC and servlets

1. Review MVC

The MVC pattern represents the Model-View-Controller pattern. This software design pattern is used for layered development of applications.

  • Model: Data Model, which provides the data to be presented and therefore contains the data and behavior, can be thought of as a domain Model or JavaBean component (containing the data and behavior), but is now generally separated: Value Object (Data Dao) and behavior 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 a user request and jumps (forwards, redirects) it to the model for processing. After the corresponding code is processed by the business layer, the controller controls the jump of the view, and the view is responsible for display. So the controller is doing the job of a dispatcher.

    The Controller features:

    • Get form data
    • Invoking business logic
    • Redirect to the specified page

1.1 Model1 and Model2

In the early development of Java Web, the unified display layer, control layer, data layer operations are all handed over to JSP or JavaBean for processing, we call Model1:

  • Disadvantages:
  • There is heavy coupling between JSPS and Java beans, and Java code and HTML code are also coupled together
  • Developers are required not only to master Java, but also to have advanced front-end skills
  • The front end and the back end depend on each other. The front end needs to wait for the back end to complete, and the back end also depends on the front end to complete in order to conduct effective testing
  • Code is hard to reuse

Because of these drawbacks, this approach was soon replaced by Servlets + JSPS + Java beans, and the early MVC model (Model2) looked like this:

First, the user’s request will arrive at the Servlet, and then invoke the corresponding Java Bean according to the request, and hand all the display results to the JSP to complete. This pattern is called MVC pattern. The most typical MVC pattern is JSP+Servlet+JavaBean pattern

2. Review servlets

Click to browse Servlet knowledge, please understand

3. What is SpringMVC

  • Spring MVC, a successor to the Spring Framework, is a lightweight Web framework that implements MVC based on Java.

  • Spring MVC implements a lightweight Web framework based on the request-driven type of Web MVC design pattern. It decoupled the responsibilities of the Web layer. Request-driven refers to the use of a request-response model, which is designed to help simplify development.

  • The Spring MVC framework is a request-driven Web framework that uses the front-end controller (DispatcherServlet) pattern to design and then distributes the request mapping rules to the corresponding page controller (action/processor) for processing.

  • Spring MVC does request processing primarily through annotations in controller, a front-end controller. Whatever request is made by the front end, it is processed lightly by the controller, forwarded, and processed by the processor at the back end, which finally returns the correct view and response. In this way, springMVC says it can either return appropriate pages or respond to RESTful requests.

Spring MVC official documentation

Spring MVC Chinese documentation

Advantages of SpringMVC:

  • Lightweight and easy to learn
  • Efficient, response-based MVC framework
  • Seamless integration with Spring (e.g. IoC container, AOP)
  • Convention over Configuration
  • Powerful: support RESTful, data validation, formatting, localization, subject and so on
  • Concise and flexible

4, HelloSpringMVC

My first Spring MVC application:

1. Configure the environment

Create a New Maven project, import dependencies (actually you can directly create Spring MVC project in IDEA, because of the beginner, please understand)

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.3</version>
        </dependency>
Copy the code

2. Configure DispatcherServlet 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">
<! - the configuration DispatcherServlet -- -- >
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <! Associated with a SpringMVC configuration file: -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <! Set the startup level to 1. When the server starts, the servlet starts too -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <! --/ match only all requests (excluding.jsp) -->
        <! --/* Match all requests (including.jsp) -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
Copy the code

3. Write the SpringMVC configuration file springmVC-servlet.xml


      
<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">
<! -- Add Handler Handler-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<! HandlerMapping DispatcherServlet calls the adapter HandlerMapping finds the Handler based on the URL request.
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<! Add 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>
 <! Register in the Spring container -->
    <bean id="/hello" class="com.cheng.controller.HelloController"/>
</beans>
Copy the code

4. Write controllers to operate services

package com.cheng.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

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

// Either implement the Controller interface or add annotations
public class HelloController implements Controller{

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // return the ModelAndView ModelAndView
        ModelAndView mv = new ModelAndView();
        // Encapsulate the object in the Model of the ModelAndView
        mv.addObject("msg"."HelloSpringMVC");
        // Encapsulate the View to jump to and place it in the View of ModelAndView
        mv.setViewName("hello");// Concatenate the view name/web-INF/JSP /hello.jsp with the view parser
        returnmv; }}Copy the code

When you’re done, register with springMVC-servlet.xml

5. Write a page to jump to

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

6. Configure Tomcat and start the test

If 404 appears, go to Project Structure >Artifacts > Manually import dependencies, and then restart the Tomcat test

DispatcherServlet:

The Spring MVC framework, like many other Web MVC frameworks, is request-driven; The design revolves around a central Servlet that distributes all requests to the controller; It also provides other functions required by Web application development. But Spring’s central processing unit, DispatcherServlet, can do more than that. It integrates seamlessly with the Spring IoC container, which means that you can use any feature Spring provides in Spring MVC.

The DispatcherServlet is just a Servlet (it inherits from the HttpServlet base class), as shown below:

The following figure shows the workflow of Spring Web MVC’s DispatcherServlet handling requests. DispatcherServlet ‘applies a’ front controller ‘design pattern.

5. How SpringMVC works

Below is a more complete flowchart for SpringMVC.

The working principle is described as follows:

  1. The user sends a request to the server, which is captured by the Spring front-end control Servelt DispatcherServlet. The DispatcherServlet represents the front-end controller and is the control center of the whole SpringMVC.

    We assume that the requested url is: http://localhost:8080/SpringMVC/hello

    The above URL is divided into three parts:

    http://localhost:8080 Server domain name

    SpringMVC is deployed on a web site on a server

    Hello means controller

    Through analysis, the above URL is represented as: Request the Hello controller of SpringMVC site on server localhost:8080;

  2. The DispatcherServlet parses the request URL to get the request resource Identifier (URI). Based on this URI, the DispatcherServlet then calls the HandlerMapping (processing mapper) to find the Handler.

  3. HandlerExecution refers to a specific Handler that is found. The main purpose of HandlerExecution is to find a controller based on a URL, such as Hello.

  4. HandlerExecution passes parsed information to the DispatcherServlet, such as parsing controller mappings;

  5. A HandlerAdapter represents a processor adapter that ADAPTS to a Handler (that is, a Controller) according to specific rules.

  6. Handler tells a specific Controller to execute,

  7. When the Controller completes execution, it returns a ModelAndView object to the HandlerAdapter with execution information.

  8. The HandlerAdapter passes the view logical name or model to the DispatcherServlet;

  9. The DispatcherServlet calls the ViewResolver to resolve the logical view name passed by the HandlerAdapter;

    What the parser does

    • Get the ModelAndView data
    • Resolve the view name of ModelAndView
    • Concatenate the view name to find the corresponding view
    • Render data to this view
  10. The view parser passes the parsed logical view name to the DispatcherServlet.

  11. The DispatcherServlet invokes specific views based on the view results parsed by the view parser

  12. Finally, render results are returned to the client.

The above code is written just to get a better understanding of how things work; it would be much simpler in real development

The annotated version implements SpringMVC

Annotated version development is much easier than the original development above

1.2.5 Importing dependencies,web.xml configuration and jump view are the same as in the above example

3. Write the SpringMVC configuration file springmVC-servlet.xml


      
<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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://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.cheng.controller"/>
    <! Let Spring MVC not handle static resources like.css,.html,.mp3,.js-->
    <mvc: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 automate the injection of the above two instances. -->
    <mvc: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. Write the controller HelloController

package com.cheng.controller;

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

The @controller annotation indicates that a class exists as a Controller
@Controller
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/hello1")// Use the @requestMapping annotation to map a request URL such as /hello to an entire class or to a specific processor method.
    / / if the writing class level request mapping, then the real request path method level for http://localhost:8080/s2/hello/hello1
    public String hello(Model model){
        // Encapsulate data
        String msg = "hello SpringMVC annotation";
        model.addAttribute("msg",msg);

        return "hello";// Returns the view name, which is processed by the view resolver}}Copy the code

Test 6.