SpringMVC: from entry to proficiency

1. What is SpringMVC?

     SpringMVC is a powerful and flexible web framework provided by Spring. With the help of annotations, Spring MVC provides an almost POJO development model [POJO refers to simple Java objects (Plain Old Java Objects, pure old java object or plain ordinary java object) . The intrinsic meaning of POJO refers to Java objects that do not inherit from any class, do not implement any interface, and have not been invaded by other frameworks. POJO allows developers to focus on business logic and unit testing outside the framework. POJO can be regarded as an ordinary Java class. It has a simple, flexible and extensible programming model, allowing developers to focus on the implementation of business logic without having to consider too much framework-related specifications and restrictions], making Controller development and testing is simpler. It is a request-driven lightweight Web framework based on Java that implements the MVC design model. It is a follow-up product of Spring Framework and has been integrated into Spring Web Flow. You can think of SpringMVC as a controller, which is responsible for processing users. Request and return a response. In SpringMVC, the controller, view and model are separated. The controller is responsible for processing user requests and returning responses, the view is responsible for displaying data, and the model is responsible for storing data.

2. Why use SpringMVC

Clear role division: SpringMVC maps controller, validator, command object, form object, model object, Servlet distributor (DispatcherServlet), and processor (handler mapping), view resolver, etc. Each role can be implemented by one or more components. This design allows developers to focus more on the implementation of business logic.

No configuration required: SpringMVC is a typical lightweight MVC framework. Compared with the previous struts2 framework, SpringMVC runs faster and its annotation-based development is more efficient and flexible. Can be seamlessly integrated with the Spring framework

High code reusability: SpringMVC supports RESTful style URL design and parameter passing, which makes the code very readable and maintainable

Easy to test: SpringMVC supports testing frameworks such as JUnit and Mockito, which makes unit testing more convenient for developers

3. SpringMVC workflow [with super detailed flow chart]

Process explanation: 

  • When a user sends a request, the first thing that enters is the front-end controller DispatcherServlet.

  • The front-end controller (DispacherServlet) sends the request from the user to the processor mapper (HandlerMapping)

  • 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.

  • After the processor adapter receives the execution chain from the front-end controller, it finds the specific controller (that is, its corresponding method or logic) that is called by the processor adapter (HandlerAdapter) that executes this execution chain.

  • The handler adapter (HandlerAdaptoer) will call the corresponding specific Controller (processing business logic)

  • After the controller is executed, a ModelAndView object will be returned to the processor adapter.

  • The processor adapter returns the returned ModelAndView object to the front-end controller (all business processing processes are completed here, and the next step is to respond to the user in the form of a page)

  • The front-end controller hands the returned ModelAndView object to the view resolver (ViewResolver), and the view resolver parses the passed View object into the corresponding page object.

  • ViewResolver will return the encapsulated page object and Model object to DISpatcherServlet

  • The front-end controller then hands the returned object to the view (View)

  • The view renders the page again (filling the model data into the view) based on the passed Model object, and then returns it to the front-end controller.

  • The front-end controller responds to the browser with the completed result, and then the browser displays it to the user.

4. SpringMVC core components

  • DispatcherServlet

DispatcherServlet is the front-end controller in the SpringMVC framework

Function: Unified processing of requests and responses from users, equivalent to an intermediate converter, reducing scheduling between various components and reducing coupling.

  • HandlerMapping

HandlerMapping is the processor mapper in the SpringMVC framework

Function: Find the corresponding Handler according to the URL and method sent by the request (that is, there will be many methods and logic in a project using the SpringMVC framework. The function of this component is to find the corresponding methods and components and return them to the front-end controller)

  • Handler

Handler processor, please note that this needs to be developed by engineers themselves.

Function: Under the control of DispatcherServlet, Handler processes specific user requests.

  • HandlerAdapter

HandlerAdapter is a processor adapter provided by the SpringMVC framework

Function: Based on the processor Handler information found by the mapper, execute the relevant processor Handler according to specific rules.

  • ViewResolver

ViewResolver is the view resolver provided by the SpringMVC framework

Function: As the name suggests, it is used to parse the processing results into views to display to the user. The view parser parses the logical view name into a physical view name, generates a View object, and finally renders the view and responds to the user.

  • View

View is a view provided by the developer itself

Function: Render the page according to the requirements of the model object, and then the front-end controller responds to the user.

5. A small introductory case of SpringMVC

pom.xml imports related dependencies

<!-- jstl-->
<jstl.version>1.2</jstl.version>
<!-- standard -->
<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>

Create springmvc.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.liwen"/>
 
    <!--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>

Configure web.xml

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

5.1. Use SpringMVC annotations to configure the Web layer

package com.liwen.web;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

 
@Controller
@RequestMapping("/mvc")
public class Springmvc1 {
    @RequestMapping("/print")
    public String test(){
        return "hello";
    }
}

jsp page


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>SpringMVC测试</title>
</head>
<body>666</body>
</html>

 

6. Annotations in SpringMVC

  • 1. @Controller: Used to mark a class. The class marked with it is a SpringMVC Controller object. The dispatch processor will scan for classes using this annotation and register it as a controller 
  • 2. @RequestMapping: used to map request paths and methods for processing requests 
  • 3. @RequestParam: used to obtain values ​​from request parameters. You can specify the name of the parameter, whether it is required, the default value, etc.
  • 4. @PathVariable: used to get the parameter value in the URL, you can specify the name of the parameter
  • 5. @ModelAttribute: used to bind request parameters to the model object
  • 6. @RequestBody: used to bind data in the request body to method parameters
  • 7. @ResponseBody: used to bind the method return value to the response body

7. SpringMVC handles static resources

   If you cannot access static resources, it is because DispatcherServlet intercepts all requests and access to static resources. Just add the following line.

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

Guess you like

Origin blog.csdn.net/Ying_hao_kun/article/details/132678992