The Road to Java——Basic Detailed Explanation of SpringMVC

Insert image description here


Preface

Spring MVC是一个用于构建Web应用程序的基于MVC(Model-View-Controller)设计模式的框架。It is part of the Spring Framework and provides a flexible, extensible and powerful way to develop Java web applications.

The following are the main features and core components about Spring MVC:
特点:

解耦合:Spring MVC is decoupled from specific view technologies and can easily switch between different view renderers, such as JSP, Thymeleaf, Freemarker, etc.

基于注解:By using annotations, configuration can be simplified and development efficiency improved. For example, the controller class is declared through the @Controller annotation, and the @RequestMapping annotation maps the URL request.

强大的数据绑定和验证:Spring MVC provides data binding and validation functions to make processing form data more convenient and secure.

内置支持RESTful风格:Spring MVC natively supports processing RESTful style requests and provides the @RestController annotation to make writing RESTful APIs more concise.

拦截器支持:Through the interceptor (Interceptor), pre-processing and post-processing can be performed at various stages of request processing to achieve unified processing logic, such as authentication, logging, etc.

With Spring MVC, developers can organize web applications with concise code and achieve good layering and testability


1. Core components

DispatcherServlet: The central scheduler is responsible for accepting all requests and scheduling the execution of other components. It is responsible for assigning user requests to the corresponding controllers for processing. It can also reduce the coupling between different components. It is the core module of the entire Spring MVC.

Handler: Processor , completes specific business logic and data processing, equivalent to Servlet

HandlerMapping:Used to map all requests to the corresponding controller processing methods. Spring MVC's HandlerMapping can be configured with multiple handlers to support different URL mapping methods.

HandlerInterceptor:Processor interceptor is an interface. If we need to perform some interception processing, we can complete it by implementing this interface.

HandlerExecutionChain:The processor execution chain includes two parts: Handler and HandlerInterceptor (the system will have a default HandlerInterceptor. If there is additional interception processing, you can add an interceptor to set it up)

HandlerAdapter:Processor adapter , before Handler executes the business method, it needs to perform a series of operations including form data verification, data type conversion, encapsulating form data into POJO, etc. These series of operations are completed by HandlerAdapter. DispatcherServlet performs different operations through HandlerAdapter. Handler. That is to say, the controller processing method is encapsulated into a processor, and multiple processors are supported at the same time to support different controller processing methods.

ModelAndView:Encapsulates model data and view information , and returns it to DispatcherServlet as the processing result of Handler.

ViewResolver:View parser , through which DispatcherServlet parses logical views into paths to physical views.

View:Responsible for rendering the data model and generating the final response result, which can be an HTML page or other types of data formats.

In Spring MVC, we usually need to define a controller to handle requests, and we can identify a controller through the @Controller annotation. The processing method in the controller uses the @RequestMapping annotation to map the request URL, and obtains information such as request parameters and path variables through @RequestParam and other annotations. Model data can be passed to the view template for rendering through ModelAndView or ModelMap.

In addition to the above core components, Spring MVC also provides many other functions and extension points, such as data binding, form validation, file upload, exception handling, internationalization support, etc., to meet the needs of various web applications.


2. Basic implementation process

1. The client request is received by DispatcherServlet

2. Based on these requests, HandlerMapping maps the request path groups to different Handlers.

3. Handler and HandlerInterceptor are returned to DispatcherServlet in the form of HandlerExecutionChain

4. DispatcherServlet calls the Handler method through HandlerAdapter to complete business logic processing

5. Return a ModelAndView object to DispatcherServlet

6. DispatcherServlet passes the obtained ModelAndView object to the ViewResolver view parser to parse the logical view into a physical view.

7. ViewResolver returns a View for view rendering (filling the model into the view)

8. DispatcherServlet responds to the client with the rendered view

Insert image description here

In the above workflow, DispatcherServlet acts as the central dispatcher, responsible for receiving client requests and distributing the requests to the corresponding Controller for processing. HandlerMapping and ViewResolver are responsible for parsing request information and view information, and routing the request to the correct Controller and corresponding view template for processing. The Controller is responsible for processing business logic and encapsulating model data and view names through ModelAndView. Finally, DispatcherServlet renders the view and returns it to the client.

The key components involved in the entire process include DispatcherServlet, HandlerMapping, HandlerAdapter, Controller, ViewResolver and View, etc. The Spring MVC framework is very flexible in processing requests and can support different URL mapping methods by configuring multiple HandlerMapping, HandlerAdapter and ViewResolver. and controller processing methods.

3. Basic configuration and use of MVC

1. Import dependencies: Add Spring MVC dependencies in the project's build tool (such as Maven, Gradle) configuration file

<?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</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringMVC Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
   <!--mvc支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.19</version>
    </dependency>

  </dependencies>
</project>

2. Configure web.xml: Configure DispatcherServlet in the web.xml file as the central dispatcher.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

<!--  配置springmvc的核心servlet-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
<!--      告诉springmvc配置文件的位置-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
<!--    拦截所有请求-->
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

3. Create a Spring MVC configuration file: Create a Spring MVC configuration file at the location specified in the above configuration and configure various components.

<?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/mvc/spring-mvc.xsd">

<!--  1. 开启注解扫描-->
  <context:component-scan base-package="com.lin.controller"/>
<!--  2. 配置处理器映射器-->
<!--  <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />-->
<!--  3. 开启处理器适配器-->
<!--  <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />-->
<!--  上面两段配置被下面的一句话所替代(封装)-->
  <mvc:annotation-driven />
  <!--  4. 开启视图解析器-->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
</beans>

4. Create a controller: Create a controller class that handles requests in the specified controller package path, and add annotations to identify it as a controller.

@Controller
public class HomeController {
    
    
    @RequestMapping("/")
    public String home() {
    
    
        return "home";
    }
}

5. Create a view: Create the corresponding JSP view file based on the view parser in the above configuration.

6. Run the application: Deploy the project to the server, start the server, and access the corresponding URL to see the processed view.

The above are the basic process steps of springmvc. The detailed process requires more study by friends.

Guess you like

Origin blog.csdn.net/m0_68987535/article/details/131342699