Spring MVC learning summary (1): Introduction to Spring MVC and entry cases

1. Introduction to Spring MVC

1. MVC mode

       The MVC we often say is the abbreviation of Model, View, and Controller, which represent the three responsibilities in Web applications.

  • Model: Encapsulate and map data. Mainly used to store data and process the business logic of user requests.
  • View: The interface shows the work. Mainly submit data to the controller and display the data in the model.
  • Controller: Control of the jump logic of the entire website. According to the request made by the view, it is judged which model to pass the request and data to for processing, and which view to update and display the relevant results after processing.

       The specific implementation of the Servlet-based MVC pattern is as follows:

  • Model: One or more JavaBean objects, used to store data (entity model, created by JavaBean class) and process business logic (business model, created by general Java class).
  • View: One or more JSP pages that submit data to the controller and provide data display for the model. JSP pages mainly use HTML tags and JavaBean tags to display data.
  • Controller: One or more Servlet objects are controlled according to the request submitted by the view, that is, the request is forwarded to the JavaBean that processes business logic, and the processing result is stored in the entity model JavaBean, and output to the view for display.

       The process of the Servlet-based MVC pattern is as follows:

2. Introduction to Spring MVC

       The Spring framework provides a full-featured MVC module for building web applications, namely Spring MVC. The Spring MVC framework provides a DispatcherServlet as a front controller to dispatch requests. At the same time, it provides flexible configuration handler mapping, view analysis, language environment and theme analysis, and supports file upload. The advantages are as follows:

(1) Clear role division : controller (controller), validator (validator), command object (command obect), form object (form object), model object (model object), Servlet distributor (DispatcherServlet), processor Handler mapping, view resoler, etc. Each role can be realized by a specialized object.

(2) Powerful and direct configuration method: Both the framework class and the application class can be configured as JavaBeans, supporting references across multiple contexts, for example, references to business objects and validators in the web controller.

(3) Adaptable and non-intrusive: According to different application scenarios, you can choose the controller subclass (simple type, command type, from type, wizard type, multi-action type or custom) instead of a single Controllers (such as Action/ActionForm) inherit.

(4) Reusable business code: You can use existing business objects as command or form objects without the need to extend the base class of a specific framework.

(5) Customizable binding and validation: For example, the type mismatch is regarded as an application-level validation error, which can guarantee the wrong value. Another example is the localized date and number binding and so on. In some other frameworks, you can only use the string form object, and you need to manually parse it and convert it to a business object.

(6) Customizable handler mapping and view resolution: Spring provides from the simplest URL mapping to complex and dedicated customized strategies. Compared with some web MVC frameworks that force developers to use a single specific technology, Spring is more flexible.

(7) Flexible model conversion: In the Springweb framework, Map-based key/value pairs are used to achieve easy integration with various view technologies.

(8) Customizable localization and theme (theme) analysis: support for optional use of Spring tag libraries in JSP, support for JSTL, support for Velocity (no additional middle layer required), etc.

(9) Simple and powerful JSP tag library (Spring Tag Library): Support includes many functions such as data binding and theme. He provides maximum flexibility in marking.

(10) JSP form tag library: The form tag library introduced in Spring 2.0 makes it easier to write forms in JSP.

(11) The life cycle of Spring Bean: It can be limited to the current HTTP Request or HTTP Session. To be precise, this is not a feature of the Spring MVC framework itself, but should belong to the WebApplicationContext container used by Spring MVC.

Two, Spring MVC entry case

1. Demonstration of helloWorld program

(1) Create a maven project and import the jar package in pom.xml.

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>

(2) Configure DispatcherServlet in the web.xml file, the specific content is as follows:

<?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_4_0.xsd"
         version="4.0">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--  指定Spring MVC配置文件的位置    -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--  
      Servlet一般都是在第一次访问时才加载,此配置表明容器在启动时就立即加载Servlet 
      load-on-startup:服务器启动时创建对象,值越小优先级越高,越先创建对象 
    -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <!--  
        /*和/都是拦截所有请求
        /*:拦截到所有的请求,包括jsp,如果不写,默认值
        /:拦截除*.jsp之外的所有请求
     -->
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

(3) Add a hyperlink jump in index.jsp, and create a pages directory under WEB-INF to establish helloPage.jsp.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
<%--SpringMVCStudy_war/--%>
<a href="${pageContext.request.contextPath}/hello">你好</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>helloPage</title>
</head>
<body>
<h3>我是helloPage,你好</h3>
</body>
</html>

(4) Create the HelloController class

@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(){
        System.out.println("我是控制台输出");
        return "helloPage";
    }
}

(5) Create a springmvc.xml file in the resources directory.

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    <!--  配置注解扫描的包  -->
    <context:component-scan base-package="com.yht.example1"></context:component-scan>
    <!--  配置视图解析器 :拼接页面地址 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--    访问路径的前缀    -->
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <!--    文件后缀    -->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

       Description: The view parser is an important part of Spring MVC. The prefix=/WEB-INF/pages/, suffix=.jsp is defined in the above configuration file by configuring the view parser. Click on the jump in index.jsp to request the hello request sent to the control layer, and return the name of the target page through sayHello(), where prefix and suffix are used to form a spelling operation (/WEB-INF/pages/helloPage .jsp) and return to the client.

 (6) Configure the tomcat server and start the project.

After startup, the index interface is displayed, click on the hyperlink.

2. Summary of the problem

(1) Description of the springmvc.xml configuration file.

If you do not specify the path of springmvc.xml when configuring the servlet in web.xml, the configuration file named dispatcherServlet-servlet.xml will be found in the WEB-INF directory by default. The error message is as follows:

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)

Solution 1: Specify the path of springmvc.xml in init-param.

Solution 2: Create dispatcherServlet-servlet.xml in the WEB-INF directory

(2) Parsing error: $%7BpageContext.request.contextPath%7D.

pageContext is parsed as $%7BpageContext.request.contextPath%7D, as shown below:

Reason: The web project generated by archetype-webapp, the default web version is 2.3, which is too low.

Solution: Change the version to a higher version, such as: 4.0

<?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_4_0.xsd"
         version="4.0">
  
</web-app>

(3)出现问题:No mapping found for HTTP request with URI [/SpringMVCStudy_war/] in DispatcherServlet with name 'dispatcherServlet'

Reason: The dispatcherServlet configuration in web.xml is incorrect. Because /* means to match all, all incoming paths will be matched and then handed over to DispatcherServlet for processing, and "/ means that DispatcherServlet is used as the default Servlet, and all other path mappings are not matched before they are handed over to it for processing.

Wrong configuration:

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

Correct configuration:

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

Three, Spring MVC workflow understanding

1. Common components

(1) DispatcherServlet : As the front controller, the center of the entire process control, it controls the execution of other components, unified scheduling, reduces the coupling between components, and improves the scalability of each component. When the user's request reaches the front controller, dispatcherServlet calls other components to process the user's request and decide the next operation.

(2) ViewResolver : Perform view resolution and resolve it into a real view based on the logical view name. The ViewResolver is responsible for generating the View view from the processing result. It first resolves the physical view name (ie the specific address of the page) according to the logical view name, then generates the View view object, and finally renders the View to display the processing result to the user through the page.

(3) HandlerMapping : HandlerMapping is responsible for finding the Handler processor according to the user's request. Spring MVC provides different mappers to implement different mapping methods, such as: configuration file mode, implementation interface mode, annotation mode, etc.

(4) HandlAdapter : execute Handler according to specific rules. The adapter mode is embodied here, and more types of processors can be executed by extending the adapter.

2. Work flow

The working principle diagram of Spring MVC is as follows:

As you can see from the above figure, the specific steps of Spring MVC work are as follows:

(1) The user sends a request to the front controller DispatcherServlet. (Click on the hyperlink in index.jsp to initiate a request for /hello)

(2) DispatcherServlet receives the request to call the HandlerMapping processor mapper. (The dispatcherServlet configured in web.xml)

(3) The processor mapper finds the specific processor (you can find it according to the xml configuration and annotations), generates the processor object and the processor interceptor (if there is one) and returns it to the DispatcherServlet.

(4) DispatcherServlet calls the HandlerAdapter processor adapter.

(5) HandlerAdapter calls a specific processor (Controller, also called back-end controller) through adaptation. (Go to HelloController to find whether the /hello request can be processed)

(6) Controller execution completes and returns to ModelAndView. (Return WEB-INF/pages/helloPage.jsp)

(7) HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet.

(8) DispatcherServlet passes ModelAndView to ViewReslover view resolver.

(9) ViewReslover returns to the specific View after parsing.

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

(11) DispatcherServlet responds to users.

 

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/112946994