[SpringMVC] workflow and entry case

Table of contents

    foreword                                                                                            

    Review the MVC three-tier architecture                                                                               

    1. Introduction to Spring MVC                                                                        

    1.1 Features of Spring MVC                                                                              

    1.2 SpringMVC core components                                                                           

    1.3 Spring MVC workflow                                                                           

    2. SpringMVC entry case                                                                 

    2.1 Add pom.xml dependency 

    2.2 Create spring-mvc.xml 

    2.3 Configure web.xml 

    2.4 Write a processor class 

    2.5 Write hello.jsp 

    2.6 Running tests 

    2.7 Static resource processing 


    foreword                                                                                            

        Spring MVC (Model-View-Controller) is a Java-based web application framework that is part of the Spring framework. It is mainly used for web development. It encapsulates Servlet, and can also be understood as an enhanced version of Servlet.

    Review the MVC three-tier architecture                                                                               

Before learning SpringMVC, let's review the idea of ​​custom MVC framework:

The basic workflow of a custom MVC framework is as follows:

  1. The user interacts with the application through the view, and the view passes the user's request to the controller.
  2. The controller receives the user request, decides which model to call to process the request according to the type and content of the request, and decides which view needs to be updated according to the processing result.
  3. In the process of processing requests, the model may need to interact with databases or other data sources to obtain the required data and perform corresponding processing. When processing is complete, return the result to the controller.
  4. Based on the processing results of the model, the controller decides which view to update to display the results to the user.
  5. After receiving the instructions from the controller, the view performs corresponding processing and rendering according to the content to be displayed, and finally presents the result to the user.

 

        In custom MVC, each request needs to write a Servlet, which is obviously inconvenient. The workflow of SpringMVC is similar to this. The controller can handle multiple requests, distribute the requests, and perform different business operations. It has been enhanced to make development more convenient.

    Introduction to Spring MVC                                                                        

        Spring MVC (Model-View-Controller) is a Java-based web application framework that is part of the Spring framework. Spring MVC provides a simple, flexible and powerful model for building web applications, which follows the MVC design pattern. This pattern helps to separate the presentation layer, business logic layer and data access layer of the application, making the development more modular and easier to maintain.

    Features of Spring MVC                                                                              

        A core principle of Spring MVC is separation of concerns, separating different aspects of an application for better code management and maintenance. It does this by dividing the application into three parts: Model, View, and Controller.

  1. Model (Model): The model represents the data and business logic of the application. It can be a POJO (Plain Old Java Object) or a persistent entity class. The model is responsible for reading, storing and validating data, and providing data to the view for display.

  2. View (View): The view is responsible for displaying the data in the model to the user. It can be a JSP (JavaServer Pages), HTML page or a page generated by other template engines. Views are usually dynamically generated based on model data in order to present the data to the user.

  3. Controller (Controller): The controller is responsible for processing user requests and coordinating the interaction between the model and the view. It receives the user's request, calls the appropriate model to process the data, and selects the appropriate view to display the result. Controllers can also handle form validation, exception handling, and other request-related logic.

    SpringMVC core components                                                                           

The Spring MVC framework provides a set of core components to implement this model-view-controller architecture. These include:

  1. DispatcherServlet: It is the front controller of Spring MVC and is responsible for receiving all HTTP requests and dispatching them to appropriate handlers.

  2. HandlerMapping: It is responsible for mapping requests to appropriate handlers (controllers).

  3. Controller: It is the interface of the handler, which is responsible for handling user requests and returning appropriate models and views.

  4. ViewResolver: It is responsible for resolving logical view names into actual view objects.

  5. View: It is responsible for rendering the model data into the final response result, which can be JSP, HTML page or other types of views.

        In addition to these core components, Spring MVC also provides many other features, such as data binding, form processing, file uploading, interceptors, internationalization support, etc., to help developers build web applications more easily.

 

    Spring MVC workflow                                                                           

  1. When the user sends a request, the first thing to enter is the front controller DispatcherServlet
  2. The front controller (DispacherServlet) sends the request from the user to the processor mapper (HandlerMapping)
  3. The processor mapper finds the corresponding controller (Handler) according to the user's request sent by the front-end controller, and encapsulates it into a processor execution chain, and returns it to the front-end controller.
  4. After the processor adapter receives the execution chain from the front controller, it finds the specific controller (that is, its corresponding method or logic) called by the processor adapter (HandlerAdapter) corresponding to the execution chain.
  5. The processor adapter (HandlerAdaptoer) will call the corresponding specific Controller (processing business logic)
  6. After the controller is executed, it will return a ModelAndView object to the processor adapter
  7. The processor adapter returns the returned ModelAndView object to the front controller (all the business processing will be finished here, and the next step is to respond the result to the user in the form of a page)
  8. The front controller passes the returned ModelAndView object to the view resolver (ViewResolver), and the view resolver resolves the corresponding page object according to the passed View object
  9. ViewResolver will return the encapsulated page object and Model object to DIspatcherServlet
  10. The front controller then hands the returned object to the view (View)
  11. The view renders the page again according to the passed Model object (fills the model data into the view), and then returns to the front controller.
  12. The front controller responds to the browser with the completed result, and then the browser displays it to the user.

 

    SpringMVC entry case                                                                 

    Add pom.xml dependency 

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>mybatis_spring</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>mybatis_spring Maven Webapp</name>
  <url>http://maven.apache.org</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>
        <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>

        <!--添加jar包依赖-->
        <!--1.spring 5.0.2.RELEASE相关-->
        <spring.version>5.0.2.RELEASE</spring.version>

        <!-- jstl+standard -->
        <jstl.version>1.2</jstl.version>
        <standard.version>1.1.2</standard.version>
        <!-- spring -->
        <spring.version>5.0.2.RELEASE</spring.version>
    </properties>


    <dependencies>
        <!--1.spring相关-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <!-- spring mvc相关依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${standard.version}</version>
        </dependency>
    </dependencies>

  <build>
      <finalName>mybatis_spring</finalName>
  </build>
</project>

The two jar packages lacking jstl+standard will report java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config, that is because org.springframework.web.servlet.view.JstlView needs this in view parsing Two jar packages.

    Create spring-mvc.xml 

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns="http://www.springframework.org/schema/beans"
       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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <context:component-scan base-package="com.ycxw"/>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <mvc:annotation-driven/>

    <!--3) 创建ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--4) 单独处理图片、样式、js等资源 -->
    <!-- <mvc:resources location="/css/" mapping="/css/**"/>
     <mvc:resources location="/js/" mapping="/js/**"/>
     <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>-->
</beans>

explain:

This code is an XML configuration file for a Spring MVC application. It is used to configure some basic settings of Spring MVC, including component scanning, annotation driving, view resolver and static resource handling. Here is a line-by-line explanation of this code:

  1. <context:component-scan base-package="com.ycxw"/>: Enable component scanning, let Spring automatically scan all classes in the specified package (here com.ycxw) and its subpackages, identify and register classes with specific annotations (such as @Controller, @Serviceetc.) as beans in the Spring container.

  2. <mvc:annotation-driven/>: Enable the annotation-driven function of Spring MVC, and let Spring MVC automatically register the default processor mapping ( DefaultAnnotationHandlerMapping) and processor adapter ( AnnotationMethodHandlerAdapter) to support annotation-based controller methods.

  3. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">: Define a view resolver ( InternalResourceViewResolver) bean, which is used to resolve the logical view name returned by the controller into an actual view resource (such as a JSP file).

  4. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView">: Set viewClassthe properties of the view parser, specifying JstlViewthe class to use to process JSTL tags.

  5. <property name="prefix" value="/WEB-INF/jsp/"/>: Set the properties of the view resolver prefixto specify the prefix path of view resources (such as JSP files).

  6. <property name="suffix" value=".jsp"/>: Set suffixthe properties of the view resolver, and specify the suffix of view resources (such as JSP files).

  7. <!--4) 单独处理图片、样式、js等资源 -->: This is a note indicating that the following configuration is used to process static resources.

  8. <!-- <mvc:resources location="/css/" mapping="/css/**"/>: This is a commented-out configuration that, if enabled, will /css/map requests whose request path starts with /css/the static resources (such as CSS files) under the directory.

  9. <!-- <mvc:resources location="/js/" mapping="/js/**"/>: This is a commented-out configuration that, if enabled, will /js/map requests with a request path starting with /js/the static resources (such as JavaScript files) under the directory.

  10. <!-- <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>: This is a commented-out configuration, if enabled, it will map requests starting with the /images/request path to WEB-INF/images/static resources (such as image files) under the directory.

        In summary, this code configures a basic Spring MVC application, including component scanning, annotation driving, view resolver, and static resource handling.

    Configure web.xml 

Configuration steps:

  1. Configure Spring to integrate with Web projects
  2. Configure Chinese garbled filter
  3. Configure SpringMVC core controller DispatcherServlet
<?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_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <!-- Spring和web项目集成start -->
  <!-- spring上下文配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
  </context-param>
  <!-- 读取Spring上下文的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Spring和web项目集成end -->

  <!-- 中文乱码处理 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- Spring MVC servlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <!--web.xml 3.0的新特性,是否支持异步-->
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

    Write a handler class 

package com.ycxw.web;

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

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-09-04 20:11
 */
@Controller
public class HelloController {
    @RequestMapping(value="/hello")
    public String hello(){
        System.out.println("调用了hello方法...");
        return null;
    }
}
  1. @Controller: Use @Controllerthe annotation to mark this class as a Spring MVC controller. This annotation tells the Spring framework that this class will handle HTTP requests.

  2. @RequestMapping(value="/hello"): Use @RequestMappingannotations to map an HTTP request path (here it is /hello) to a method of the controller (here it is hello()method). The method will be called when the user visits /hellothe path .hello()

    Write hello.jsp 

The ViewResolver view parser has been configured in the spring-mvc.xml file

    run test 

 

    Static resource handling 

All files will be intercepted by the spring-mvc.xml configuration file, so add configuration to let the processor scan the resource

<mvc:resources location="/static/" mapping="/static/**"/>

 Such as path:

Run the test: 

Guess you like

Origin blog.csdn.net/Justw320/article/details/132677124