SMVC1: introduction, case and principle of spring MVC

1. Introduction

1.1 MVC

MVC: model (dao, service), view (jsp) and controller (servlet). MVC is not a design pattern, but an architecture pattern. Of course, in the early web development, Model1 is used. In Model1, it is mainly divided into two layers: view layer and model layer.

1.2 SpringMVC

Definition: Spring MVC is a lightweight Web framework based on java MVC.

Features: 1. Lightweight, easy to learn. 2. Efficient and request based MVC framework. 3. It is well compatible with Spring and seamlessly connected. 4. Agreement is greater than configuration. 5. Powerful functions: RESTful style (no question mark to pass parameters, slash segmentation), data verification, formatting, localization, theme, etc. 6. Simple and flexible.

1.3 spring MVC case

Maven dependency:

dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

The resource could not be exported correctly:

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

web.xml:

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

    <!--        register DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--        Associate a Springmvc Configuration file for-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
<!--        Startup level-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--The following configuration contents are:/´╝îinstead of/*-->
        <url-pattern>/</url-pattern>
        
    </servlet-mapping>
</web-app>

Tip: the difference between / * and / * is that the former can only match requests, not JSPS, while the latter can not only match requests, but also JSPS.

springmvc-servlet.xml:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    
<!--        Processor mapper-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    
    <!--        Processor adapter-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

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

    <!--The following statement is beanHandler Unique configuration of-->
    <bean id="/hello" class="com.yun.controller.HelloController"/>
</beans>

HelloController:

package com.yun.controller;

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

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


public class HelloController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();

        //Data encapsulation
        mv.addObject("msg","HelloSpringMVC");
        
//        Set the view to jump. Hello is equivalent to / Web inf / JSP / hello.jsp
        mv.setViewName("hello");
        return mv;
    }
}

hello.jsp:

<%--
  Created by IntelliJ IDEA.
  User: yun
  Date: 2021/9/22
  Time: 15:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

Tip: in the URL bar, you can directly access Hello, for example: http://localhost:8080/SpringMVC_01_servlet_war_exploded/hello. If the code is normal, the page with the words Hello spring MVC will appear. If there is no code error and the operation still fails, you need to import the war package of the project: File project structure artifacts, select the current war package, and create the lib directory in the web inf directory. Then click the plus sign, select Library files, and import all dependencies.

1.4 spring MVC implementation principle

Tip: the line of sight represents what Spring does for us, while the dotted line represents the parts that need to be implemented by ourselves.

Process:

1: Dispatcher servlet represents the front-end controller and is the control center of the whole spring MVC. When the user sends a request, the dispatcher servlet accepts the request and intercepts it.

  • The access address is: http://localhost:8080/SpringMVC_ 01_ servlet_ war_ Expanded / Hello, which can be divided into three parts.
  • Part I, http://localhost:8080 . This is the domain name server, that is, the URL and port
  • The second part, spring MVC_ 01_ servlet_ war_ exploded. This is the web site deployed on the server, that is, the name of our project.
  • The third part, hello. This is the Controller, that is, the Controller we wrote.

Summary: in short, a controller of a site in a port on a server is requested.

2: HandlerMapping is a processor mapping. It is mainly called by the DispathcerServlet, and then the HandlerMapping finds the Handler according to the request URL. That is, these two sentences in the Spring-dao.xml file work:

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

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

3: HandlerExecution represents a specific Handler. Its main function is to find a controller according to the URL, such as hello.

4: HandlerExecution passes the parsed information to the dispatcher servlet, such as parsing the controller mapping.

5: HandlerAdapter means that the processor adapter executes the Handler according to specific rules (in fact, the so-called specific rules mean that there is a controller here that needs to execute the controller).

6: In this step, the Handler lets the specific Controller execute.

7: The Controller returns the execution result to the HandlerAdapter, such as ModelAndView.

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();

        mv.addObject("msg","HelloSpringMVC");
//        Set the view to jump. Hello is equivalent to / Web inf / JSP / hello.jsp
        mv.setViewName("hello");
        return mv;
    }

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

9: DispatcherServlet calls the view parser (viewresolver) to resolve the handler adapter and pass the logical view name.

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

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

12: The final view is presented to the user.

1.5 modification cases with notes

web.xml:

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

    <!--        register DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--        Associate a Springmvc Configuration file for-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--        Startup level-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--The following configuration contents are:/´╝îinstead of/*-->
        <url-pattern>/</url-pattern>

    </servlet-mapping>
</web-app>

Tip: the configuration of the above files is basically dead, and there is only one Dispatcher servlet configuration. The main contents are: registering Srpingmvc, associating spring MVC configuration files, setting startup level and Dispatcher mapping.

springmvc-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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
        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">

<!--    Configure scanner-->
    <context:component-scan base-package="com.yun.controller"/>
<!--    Configure static resource filtering-->
    <mvc:default-servlet-handler/>
<!--    Configure process mapper and process adapter-->
    <mvc:annotation-driven/>

<!--    Configure view parser-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

Tip: because annotations are used for development, you need to configure a scanner in the spring MVC configuration file to scan annotations under a specific package. Moreover, since many static resources do not use the view parser, a static resource filter is configured (I call it this). Moreover, both the processing controller and the processing adapter can be configured using the annotation driver. However, a view parser is required. Moreover, after using annotations, the Bean between the request and the controller is not needed. This document is basically dead in terms of configuration.

HelloController:

package com.yun.controller;

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

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","Hello, this is SpringMVC");
        //The string returned here is the name of the front-end page to be returned,
        return "helloPage";
    }
}

Tip: @ Controller annotation tells Spring that this is the Controller, which is also mentioned in Spring 5. In addition to the control layer, other layers also have corresponding annotations: @ Repository, @ Service, @ Component, etc. The @ RequestMapping("/hello") replaces the bean in the original springmvc-servlet.xml file:

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

If the request has multiple levels, such as: / hello/test. At this time, the @ RequestMapping annotation should also be added to the class. The return "helloPage" statement is equivalent to the ModelAndView.setViewName("hello") statement.

helloPage.jsp:

<%--
  Created by IntelliJ IDEA.
  User: yun
  Date: 2021/9/24
  Time: 14:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

Tip: the front-end file has not changed. If the above code is completely correct, you need to check whether the war package of the project has the lib directory. If not, you need to import the war package of the project by dependency: File project structure artifacts, select the current war package, and create the lib directory under the web inf directory. Then click the plus sign, select Library files, and import all dependencies.

Keywords: Java Spring Spring MVC mvc

Added by peri on Fri, 24 Sep 2021 12:31:55 +0300