2021.11.1 purpose and operation process of Spring MVC. Run a Hello World with Spring MVC, and understand the components of Spring MVC by combining theory with code

Servlet is a protocol, framework technology, a set of standards, a set of standards for java web development, and java Dynamic web Framework Technology.

Traditional Servlet: accept the user's request, process it, and give the user a response after processing. A Servlet can only receive a corresponding user request, which will lead us to develop many servlets.

The processing of request parameters is too cumbersome. If there are 100 parameters, it is necessary to write the acquisition parameters 100 times

The emergence of spring MVC can solve the above problems. Simplify the code and save time. Simplify web development, and the request mode can write multiple requests in one class.

2. Modify the pom.xml file to download and configure the project dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>springmvc-study</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--by pom Define some common variables in pom Other parts of the can be referenced directly
    The usage is as follows: ${spring.version} -->
    <properties>
        <file.encoding>UTF-8</file.encoding>
        <java.source.version>1.8</java.source.version>
        <java.target.version>1.8</java.target.version>
        <spring.version>5.3.12</spring.version>
        <servlet.version>4.0.1</servlet.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
<!--            <version>5.3.12</version>-->
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
<!--            <version>4.0.1</version>-->
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>


Dependency packages will appear after the dependency is downloaded.

3. Create a new controller

4. Manually create a new directory

Enter the following code in the hello.jsp file:

<%@page contentType="text/html; charset=utf-8"
        pageEncoding="UTF-8" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<h1>Welcome ${name} to Spring MVC!</h1>
</body>
</html>

And add a line of code in the pom.xml configuration:

It indicates that this is a web project, and after adding this line of code,


The icon color of webapp has also changed, indicating that this is a web project

5. Next, create the spring MVC configuration file
New file spring-servlet.xml

Input:

<?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">
    <!-- Handler(processor) : name="/hello" -->
    <bean name="/hello" class="com.neu.springmvc.controller.HelloController"/>
    <!-- HandlerMapping(Processor mapper) : Bean Name Map to an accessed URL -->
    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
    <!-- HandlerAdapter(Processor adapter) -->
    <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <!-- ViewResolver(view resolver )-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

6. Create a new web.xml file that loads Spring MVC
Create a new one in the webapp/WEB-INF directory, which is the same level as jsp

<?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">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Note that if an error is reported in the file and the figure below, it can still run normally.
7. Configure Tomcat files,


After running, this interface appears

Don't panic, change the address bar and add hello

This interface appears, indicating that Spring MVC is OK


1. Dispatcher servlet: front end controller (key)
When the user's request reaches the front-end controller, it is equivalent to c in mvc mode. Dispatcher servlet is the center of the whole process control, which is equivalent to the brain of spring mvc. It calls other components to process the user's request. The existence of dispatcher servlet reduces the coupling between components.

2. HandlerMapping: processor mapper
HandlerMapping is responsible for finding the Handler, that is, the processor (that is, the Controller) according to the user's request. Spring MVC provides different mappers to implement different mapping methods, such as configuration file method, implementation interface method, annotation method, etc. in actual development, the annotation method is commonly used.

3. Handler: processor
Handler is the back-end Controller following the front-end Controller of dispatcher servlet. Under the control of dispatcher servlet, handler processes specific user requests. Since the handler involves specific user business requests, it is generally necessary for programmers to develop the handler according to business requirements. (the handler here refers to our Controller)

4. HandlAdapter: processor adapter
The processor is executed through the HandlerAdapter, which is an application of the adapter mode. More types of processors can be executed through the extension adapter.

5. ViewResolver: View resolver
ViewResolver is responsible for generating the processing results into the View view. ViewResolver first resolves the logical View name into the physical View name, that is, the specific page address, and then generates the View object. Finally, it renders the View and displays the processing results to the user through the page.

Spring MVC framework provides many View types, including jstlView, freemarkerView, pdfView, etc. Generally, the model data needs to be displayed to users through pages through page label or page template technology. Programmers need to develop specific pages according to business requirements.

1. HelloController is equivalent to a processor. Receive the user's request, process it, create a ModelAndView called hello, add a parameter to mv, the parameter name is name, the parameter value is 666, and then return to this view.

2. The view layer is in hello.jsp

Q: how is 666 in HelloController transferred to hello.jsp with these lines of code?
We will find a view parser in hello controller to parse hello into

/WEB-INF/jsp/hello.jsp

We wrote the code of the view parser in spring-servlet.xml in resources.
Where prefix is the prefix and suffix is the suffix. So hello is reorganized in this parser. By default, the location of hello.jsp is found.

The order should be front-end controller > processor mapper (Beannameurl analyzes the data of the processor, maps it to the processor) > processor > processor adapter > View parser

That is, a request first passes through the front-end controller and then to the processor mapper (HandlerMapping: Bean Name is mapped to an accessed URL)

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

The value in id cannot be modified because this is to find the specified handlerMapping. The bean is then automatically assembled to find / hello

Find the processor of / hello, and then adapt the processor.

DispatcherServlet is the implementation of the front-end controller design pattern and provides a centralized access point for Spring Web MVC,
It is responsible for the assignment of responsibilities without business logic. It is only responsible for the assignment of tasks, and is seamlessly integrated with the Spring IoC container, so as to obtain the advantages of Spring.
DispatcherServlet is mainly used for responsibility scheduling and process control. Its main responsibilities are as follows:

  1. File upload parsing. If the request type is multipart, the file will be uploaded through MultipartResolver
    Analysis;
  2. Map the request to the processor through handler mapping (return a handler execution chain, including one processor and multiple handler interceptors interceptors);
  3. Support multiple types of processors (processors in HandlerExecutionChain) through HandlerAdapter;
  4. Parse the logical view name to the specific view through ViewResolver;
  5. Localization analysis; (automatically identify and output local languages, and support various languages)
  6. Rendering specific views, etc;
  7. If an exception is encountered during execution, it will be handed over to the handler exception resolver (handler exception resolver) for parsing.
<servlet>  
    <servlet-name>springmvc</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet< /servlet-class>  
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring-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> 

Load on startup: indicates that the Servlet is initialized when the container is started;

URL pattern: indicates which requests are submitted to Spring Web MVC for processing, "/" is used to define the default servlet mapping. You can also block all requests with html extension as *. html

contextConfigLocation: indicates the path to the spring MVC configuration file

contextClass is a class that implements the WebApplicationContext interface. The current servlet uses it to create a context. If this parameter is not specified, XmlWebApplicationContext is used by default.

contextConfigLocation is a string passed to the context instance (specified by contextClass) to specify the location of the context. This string can be divided into multiple strings (using commas as separators) to support multiple contexts. (in the case of multiple contexts, if the same bean is defined twice, the latter takes precedence).

Namespace: WebApplicationContex namespace. The default value is [server name] - servlet.

Keywords: Java Spring mvc

Added by JustinK101 on Mon, 01 Nov 2021 12:45:16 +0200