Spring MVC -- [quick start, execution process, component analysis]

Keywords: Spring

catalogue

Integration of Spring and Web Environment

ApplicationContext application context acquisition method

Spring provides tools for obtaining application context

Spring MVC overview

Introduction to spring MVC

Spring MVC quick start

  Spring MVC component analysis

  1. Execution process of spring MVC

2. Spring MVC component analysis

3. Spring MVC annotation parsing

4. XML configuration parsing of spring MVC

Integration of Spring and Web Environment

ApplicationContext application context acquisition method

The application context object is obtained through the new classpathxmiaapplicationcontext (spring configuration file), but each time a Bean is obtained from the container, it is necessary to write a new classpathxmiaapplicationcontext (spring configuration file). This disadvantage is that the configuration file is loaded multiple times and the application context object is created multiple times.
In the Web project, you can use the ServletContextListener to listen to the start of the Web application. When the Web application starts, we can load the Spring configuration file, create the application context object ApplicationContext, and store it in the largest domain servletContext domain, so that the application context ApplicationContext object can be obtained from the domain at any location.

Spring provides tools for obtaining application context

The above analysis is based on the native analysis. Spring provides a listener, ContextLoaderListener, which encapsulates the above functions. The listener internally loads the spring configuration file, creates the application context object, and stores it in the ServletContext domain. It provides a client-side tool WebApplicationContextUtils for users to obtain the application context object.
So there are only two things we need to do:
1. Configure the ContextLoaderListener listener in web.xml (import spring web coordinates)

2. Get the application context object ApplicationContext using WebApplicationContextUtils
        1. Coordinates of importing Spring integrated web

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

        2. Configuring the ContextLoaderListener listener
 

    <!--Global initialization parameters-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
<!--Configure listener-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

        3. Obtain the application context object through the tool

        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = app.getBean(UserService.class);

Spring MVC overview

Introduction to spring MVC

Spring MVC is a request driven lightweight Web framework based on Java to implement MVC design model. It is a follow-up product of spring framework and has been integrated into Spring Web Flow.
Spring MVC has become one of the most popular MVC frameworks, and with the release of spring 3.0, it has comprehensively surpassed struts 2 and become the best MVC framework. Through a set of annotations, it makes a simple Java class a controller for processing requests without implementing any interface. At the same time, it also supports RESTful programming style requests.
 

Spring MVC quick start

Requirements: the client initiates the request, the server receives the request, executes logic and jumps the view.

Development steps:

1. Import spring MVC related coordinates
2. Configuring the spring MVC core controller DispathcerServlet
3. Create Controller classes and view pages
4. Use the annotation to configure the mapping address of the business method in the Controller class
5. Configure spring MVC core file spring-mvc.xml
6. Client initiated request test

1. Import spring MVC related coordinates

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.2.1</version>
      <scope>provided</scope>
    </dependency>

2. Configure the spring MVC core controller DispathcerServlet in web.xml

    <!--to configure SpringMVC Front end controller-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
     <!--Load when server starts servlet,That is, create objects-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
            <!--By default, every request comes-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

3. Creating controller s and business methods

public class QuickController {
    public string quickMethod ( ) {
    system.out.println ("quickMethod running.. ... " );
    return "index" ;
}
}

    Create view page index.jsp

<htm1>
<body>
<h2>Hello SpringMVC!</h2>
</body>
</html>

4. Configuration annotation

@Controller
public class QuickController {
    @RequestMapping ("/quick" )
    public string quickMethod ( ) {
    system.out.println ("quickMethod running.. ... " );
    return "index" ;
}
}

5. Configure spring MVC core file spring-mvc.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 http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/spring-mvc.xsd">

<!-―Configure annotation scanning-->
<context: component-scan base-package="com.longdi" / >

</bean>

6. Client initiated request test

Spring MVC process diagram:

  Spring MVC component analysis

  1. Execution process of spring MVC

(1) The user sends a request to the front-end controller DispatcherServlet.
(2) The dispatcher servlet receives a request to call the handler mapping processor mapper.
(3) The processor mapper finds the specific processor (which can be found according to the xml configuration and annotation), generates the processor object and the processor interceptor (if any) and returns it to the dispatcher servlet.
(4) Dispatcher servlet calls HandlerAdapter processor adapter.
(5) The handleradapter invokes a specific processor (Controller, also known as back-end Controller) through adaptation.
(6) The controller returns ModelAndView (model and object) after execution.
(7) The handleradapter returns the controller execution result ModelAndView to the dispatcher servlet.
(8) The dispatcher servlet passes the ModelAndView to the viewrestrover view parser.
(9) The viewrestrover returns the specific View after parsing.
(10)DispatcherServlet renders the View according to the View (that is, fills the View with model data). DispatcherServlet responds to the user.

2. Spring MVC component analysis

1. Front end controller: DispatcherServlet
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. It calls other components to process the user's request. The existence of dispatcher servlet reduces the coupling between components.
2. Processor mapper: HandlerMapping
HandlerMapping is responsible for finding the Handler, that is, the processor, according to the user's request. Spring MVC provides different mappers to implement different mapping methods, such as configuration file mode, implementation interface mode, annotation mode, etc.
3. Processor adapter: HandlerAdapter
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.
4. Processor: Handler
It is the specific business controller to be written in our development. The dispatcher servlet forwards the user request to the Handler. The Handler processes the specific user request. (similar to controller)
5. View Resolver: View Resolver
The View Resolver is responsible for generating the processing results into the View view. The View Resolver 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.
6. View: View
Spring MVC framework provides support for many View types, including jstlView, freemarkerViev, pdfView, etc. the most commonly used View is jsp. Generally, model data needs to be displayed to users through pages through page tag or page template technology, and programmers need to develop specific pages according to business needs
 

3. Spring MVC annotation parsing

@RequestMapping
Function: used to establish the corresponding relationship between the request URL and the request processing method. Location:
         Class, the first level access directory of the request URL. If it is not written here, it is equivalent to the root directory of the application
         Method, the second level access directory of the request URL and the first level directory marked with @ ReqquestMapping on the class form the access virtual path attribute:
         value: used to specify the URL of the request. It works the same way as the path attribute
         Method: used to specify the method of the request
         params: used to specify conditions that restrict request parameters. It supports simple expressions. key and value as like as two peas for the requested parameters must be exactly the same as those configured.

For example:
         params = {"accountName"}, indicating that the request parameter must have accountName
         params = {"moeny!100"}, indicating that money in the request parameter cannot be 100
1.mvc namespace introduction
 

Namespace: xmlns:context="http: // www.springframework.org/ schema/context
                xmlns:mvc="http: //www.springframework.org/schema/mvc"
Constraint address: http: //www.springframework.org/schema/context
                http: // www.springframework.org/schema/context/ spring-context.xsd
                http : // www.springframework.org/ schema /mvc
                http: // www.springframework.org/schema /mvc/spring-mvc.xsd

2. Component scan

Spring MVC is based on the spring container, so during spring MVC operation, you need to store the Controller in the spring container. If you use the @ Controller annotation, you need to use

< context: component scan base package = "com. Longdi. Controller" / > scan components.

4. XML configuration parsing of spring MVC

  view resolver

Spring MVC has default component configuration. The default components are configured in the DispatcherServlet.properties configuration file. The address of the configuration file is
org/ springframework/web/servlet/DispatcherServlet.properties. The default view parser is configured in this file, as follows:

  By browsing the parser source code, you can see the default settings of the view parser, as follows:

We can modify the pre suffix of the view by attribute injection

Posted by escocia1 on Wed, 20 Oct 2021 16:19:54 -0700