SpringMVC basic introduction and workflow---detailed introduction to all aspects

1. SpringMVC concept

Spring MVC is a lightweight web framework     based on Java that implements the request-driven type of MVC design pattern . By separating Model, View, and Controller, it decouples the responsibilities of the web layer and divides complex web applications into several parts with clear logic. part, simplifying development, reducing errors , and facilitating cooperation among developers within the team.

In addition, Spring MVC's annotation driver and support for REST style are also its most distinctive features. It completely surpasses MVC frameworks such as Struts2 in terms of framework design, scalability, and flexibility. And since Spring MVC itself is part of the Spring framework, it can be said that it is seamlessly integrated with the Spring framework and has inherent superiority in performance. For developers, the development efficiency is also higher than other Web frameworks . In enterprises, It is more and more widely used and has become the mainstream MVC framework .

2. SpringMVC workflow

Working principle diagram:

Rough process steps:

(1) The user sends a request to the front-end controller DispatcherServlet

(2) After receiving the request, DispatcherServlet calls the HandlerMapping processor mapper and requests to obtain the Handle

(3) The processor mapper finds the specific processor according to the request URL, generates the processor object and the processor interceptor (if any) and returns them to DispatcherServlet.

(4) DispatcherServlet calls HandlerAdapter processor adapter

(5) HandlerAdapter calls a specific processor (Handler, also called back-end controller) through adaptation

(6) Handler execution completes and returns to ModelAndView

(7) HandlerAdapter returns the Handler execution result ModelAndView to DispatcherServlet

(8) DispatcherServlet passes the ModelAndView to the ViewResolver view parser for parsing;

(9) ViewResolver returns the specific View after parsing

(10) DispatcherServlet renders the View (that is, fills the model data into the view)

(11) DispatcherServlet responds to users

3. Main components and functions in SpringMVC

Through the flow chart above, the components are explained accordingly:

DispatcherServlet (central controller/dispatcher Servlet):

       It is the core component of Spring MVC and is responsible for receiving all HTTP requests and distributing them to other components for processing.

HandlerMapping (processor mapper):

            Find the handler based on the requested URL

HandlerAdapter (processor adapter): execute handler

Handler (processor/controller):

          The component that actually handles the request, including the business logic layer (CRUD).

ModelAndView (model and view):

         Used to encapsulate the return result of the processor, including model data and view information. Model data is used to pass business data to the view, and view information is used to determine how to render the response results.

 

ViewResolver:

      The specific view object is parsed according to the view name, which is used to render the response result. It can be parsed based on conditions such as the type of view (JSP, Thymeleaf, Freemarker, etc.) and location

4. Introductory case demonstration

4.1 pom.xml dependencies:

<!-- jstl+standard -->
<jstl.version>1.2</jstl.version>
<standard.version>1.1.2</standard.version>
<!-- spring -->
<spring.version>5.0.2.RELEASE</spring.version>
...
<!-- 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>

The two jar packages lacking jstl+standard will report the following line of code

 java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config,

That's because org.springframework.web.servlet.view.JstlView requires these two jar packages when parsing the view.

4.2 Create 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-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.zking.ssm"/>

    <!--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>

4.3 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>

4.4 Create a back-end web and create a method

/**
 * @Name BingBing
 * @company zking cy
 * @create 2023-09-04-21:18
 */
@Controller
public class IndexController {
   @RequestMapping("/hello")
    public String hello() {
        System.out.println("Hello Spring MVC....");
        return "hello";
    }

}

The @RequestMapping annotation is an annotation used to handle request address mapping. It can be used to map a request or a method and can be used on a class or method.

Extensions:


@GetMapping: handles the mapping of get request


@PostMapping: Mapping for processing post requests


@PutMapping: Processing mapping of put request


@DeleteMapping: Mapping to handle delete request


@GetMapping is equivalent to @RequestMapping(method=RequestMethod.GET), which maps get to a specific method.
 

4.5 JSP page writing

jsp:

<%--
  Created by IntelliJ IDEA.
  User: 兵
  Date: 2023/9/4
  Time: 21:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  欢迎来到SpringMVC....
</body>
</html>

operation result: 

 5. Extension (static resource processing)

Image processing:

Add the following code in spring -mvc.xml

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

Run the test:

Pay attention to the image access path

Guess you like

Origin blog.csdn.net/m0_73192864/article/details/132677381
Recommended