Spring Mvc: Getting to Know Spring Mvc for the First Time

Compilation software: IntelliJ IDEA 2019.2.4 x64
Operating system: win10 x64-bit Home Edition
Maven version: apache-maven-3.6.3
Mybatis version: 3.5.6
SpringMvc version: 5.3.1



insert image description here


1. What is SpringMvc?

①SpringMVC is a sub-framework of Spring . It is an excellent Web framework based on the MVC design concept provided by Spring for [ presentation layer | presentation layer | presentation layer | control layer ] . It is currently the most mainstream MVC framework.

What is the Mvc design concept?

It is the Mvc design idea, namely Model (business model), View (user view) and Controller (control layer)

Why use the Mvc design concept?

Simply put, the MVC design concept provides a structured way to organize application code, enabling developers to better manage complexity, improve development efficiency, and achieve maintainable, scalable, and testable code.

②SpringMVC is non- intrusive

What is non-intrusive?

It emphasizes a development pattern, 在使用框架的同时尽量减少对应用程序代码的依赖和修改,使得框架与应用程序之间的耦合度降低。specifically, 在SpringMVC中,你可以编写普通的Java类作为控制器,并通过注解或配置将其标识为处理特定URL请求的方法. This way allows you to maintain the original structure and business logic of the application without forcing you to change the organization of the code in accordance with the framework's specifications.

③SpringMVC is used to replace Servlet . Before the SpringMvc framework is used, we usually process requests and respond based on Servlet.


2. How does SpringMvc execute business processes?

The simple process of SpringMvc executing business is as follows

insert image description here

  1. The user sends a request to the backend through the browser.
  2. DispatcherServlet is a Servlet that receives all requests as the entry point of the application and is responsible for coordinating the entire processing flow.
  3. DispatcherServlet finds the processor (controller) suitable for processing the current request according to the configured processor mapper (HandlerMapping) query.
  4. The handler mapper maps requests to appropriate handlers based on the requested URL or other criteria. A handler can be a class, usually identified with an annotation (such as @Controller), or a class that implements a specific interface (such as HandlerInterceptor).
  5. The handler mapper simply encapsulates the request to get the handler execution chain object (HandlerExecutionChain) and returns it to DispatcherServlet, which includes the handler itself, interceptors and other auxiliary processors.
  6. DispatcherServlet calls the processor's preprocessing method (preHandle) through the interceptor chain, so that it can prepare some shared data and preprocess the request.
  7. According to the processor in the processor execution chain, DispatcherServlet finds the corresponding processor adapter object HandlerAdapter. This is because there are more than one types of processors, and different processors require different processor adapters, HandlerAdapter, to execute.
  8. After finding the corresponding processor adapter, DispatcherServlet immediately calls the processor adapter to let it execute the processor.
  9. After the processor adapter executes the processor, the processor returns the ModelAndView to the processor adapter.
  10. After the processor adapter receives the ModelAndView returned by the processor, it directly returns the ModelAndView to the DispatcherServlet.
  11. After DispatcherServlet receives the ModelAndView sent by the processor adapter, it does not take it as the final scheduling result, but first calls the interceptor backend method in the execution processor execution chain. Because the DispatcherServlet passes the ModelAndView object to the backend method of the interceptor, the backend method can modify the ModelAndView.
  12. The work of the view resolver binds the view name with the response target positioning object, forms a view object and returns it to the DispatcherServlet.
  13. After obtaining the corresponding view object, DispatcherServlet calls the rendering method of the view object to actually render the view.
  14. DispatcherServlet performs finishing work, which executes the afterCompletion() method of the processor execution chain interceptor. The final response to the request is issued by the afterCompletion() method.
  15. The browser receives the response

3. How to build the first HelloWorld based on SpringMvc

3.1 Steps to build the SpringMvc framework

①Create a Maven project in IDEA and import related jar packages

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.10</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

Why set the scope of javax.servlet-api to provided here?

Because the tomcat server already has a javax.servlet-api, if the javax.servlet-api jar package dependency range is set to the Tomcat server in pop.xml, the jar packages of the two servlets will conflict.

insert image description here

② Write the configuration file

  • Register DispatcherServlet in web.xml

    • urconfig:/
      • init-param: contextConfigLocation, set springmvc, xml configuration file path [management container object]
      • <load-on-startup>: Set DispatcherServlet priority [When starting the server, create the current Servleti object]
  • Implement the following functions in springmvc.xml

    • Turn on component scanning
    • Configure View Parser [Parse View (Set View Prefix & Suffix)]

③ Write a request processor [Controller | Handler]

  • Use the @Controlleri annotation to identify request handlers
  • Use the @RequestMapping annotation to identify the processing method [URL]

insert image description here

④ Prepare the page for testing

3.2 Actual combat of HelloWorld

① preparation

Create a new Maven project and build a web project environment on it. The project structure is as follows

insert image description here

②Import related jar packages in pop.xml in Maven project

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.10</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

③Enable component scanning and configuration view parser in [springmvc.xml] in the spring configuration file

<!--  开启组件扫描  -->
<context:component-scan base-package="spring"></context:component-scan>

<!-- 配置视图解析器【解析视图(设置视图前怨后缀)】 -->
<!--  配置视图解析器  -->
<bean id="thymeleafViewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <!--鹿置字符集属性 -->
    <property name="characterEncoding" value="UTF-8"></property>
    <!--鹿置模板引擎厨性-->
    <property name="templateEngine">
        <!--鹿置内bean-->
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
            <!--鹿置馍块的解析器雨性-->
            <property name="templateResolver">
                <!--     配置内部bean       -->
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                    <!--  配置前缀        -->
                    <property name="prefix" value="/WEB-INF/pages/"></property>
                    <!--   配置后缀       -->
                    <property name="suffix" value=".html"></property>
                    <!--   配置字符集                     -->
                    <property name="characterEncoding" value="UTF-8"></property>
                </bean>
            </property>
        </bean>
    </property>
</bean>

④ Register DispatcherServlet [Front Controller] in web.xml

<!-- 注册 Dispatcherservlet【前满控制器】-->
<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:springmvc.xml</param-value>
    </init-param>

    <!--  设置DispatcherServlet优先级      -->
    <!--   启动服务器时,创建当前Servleti对象     -->
    <load-on-startup>1</load-on-startup>

</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

⑤Create a new class HelloController under /src/main/spring/Controller under the current project as a request processor, use the @Controlleri annotation to identify it as a request processor, and use the @RequestMapping annotation to identify the processing method [URL]

insert image description here

@Controller
//标识此类为请求处理器
public class HelloController {
    
    

    //配置url【/】  映射到wEB-INF/index.html
    @RequestMapping("/")
    public String toIndex(){
    
    
        //WEB-INF/pages/index.html
        //物理视图名=视图前餐+逻辑视图名+视图后缀
        return "index";
    }

    /**
     * 配置url【/HelloControllerMethod】,浏览器中的请求会基于该url,找到并进入下面的方法
     */
    @RequestMapping("/HelloControllerMethod")
    public String HelloControllerMethod(){
    
    
        System.out.println("--->请求已经进入到HelloControllerMethod方法中");
        //默认是转发请求
        return "success";
    }
}

⑥ Write related front-end pages [index.html & success.html]

<!-- index.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/HelloControllerMethod}">发送请求</a>
</body>
</html>
<!-- success.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>转发成功,到达成功页面</title>
</head>
<body>
<h1>成功页面</h1>
</body>
</html>

⑦Start the Tomcat server and run the test

insert image description here
insert image description here
insert image description here


Guess you like

Origin blog.csdn.net/siaok/article/details/131596204