Introduction to Spring MVC with an introductory case

Table of contents

1. Introduction to Spring MVC

1.1 MVC model

1.2 SpringMVC

Two, SpringMVC entry case

2.1 Create a project

2.2 Introducing dependencies and tomcat plugins

2.3 Modify the web.xml file 

2.4 Create a new springmvc.xml file

2.5 Write the controller 

2.6 Configure operation mode

2.7 Running tests 

Three, SpringMVC execution process

3.1 Components of SpringMVC

3.2 Workflow of components

Related readings of previous columns & articles 

1. Maven series of columns

2. Mybatis series of columns

3. Spring series of columns 

4. Spring MVC series of columns 


1. Introduction to Spring MVC

1.1 MVC model

The full name of MVC is Model View Controller, which is a pattern for designing and creating web applications. These three words represent the three parts of the web application:

  • Model: Refers to the data model. Business logic for storing data and handling user requests. In Web applications, JavaBean objects, business models, etc. all belong to Model.
  • View (view): used to display the data in the model, usually jsp or html files.
  • Controller (controller): is the part of the application that handles user interaction. Accept the request made by the view, hand over the data to the model for processing, and hand over the processed result to the view for display.

1.2 SpringMVC

        SpringMVC is a lightweight Web framework based on the MVC pattern. It is a module of the Spring framework and can be directly integrated with Spring. SpringMVC replaces the Servlet technology. It uses a set of annotations to make a simple Java class a controller for processing requests without implementing any interfaces.

Two, SpringMVC entry case

2.1 Create a project

Create an empty project first:

Go to Next until the picture below, and determine the project name and project location. click finish

Next, we write an introductory case of SpringMVC. At this point, we can create a new module. First, use maven to create a web project and complete the package structure.

 Click Next, as shown below 

        Because I have already built it, there is a red prompt in the box above. Configure the corresponding id, click next, you can’t click the next step if you are popular, I just changed it casually for you to see. Just know what it means.

 OK, click finish if there is no problem.

 

After it is built, it will look like the picture above 

2.2 Introducing dependencies and tomcat plugins

pom.xml file content:

<?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>com.example</groupId>
  <artifactId>mvc_demo1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

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

  <dependencies>
    <!-- Spring核心模块 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.12.RELEASE</version>
    </dependency>
    <!-- springWeb模块 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.12.RELEASE</version>
    </dependency>
    <!-- SpringMVC模块 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.12.RELEASE</version>
    </dependency>
    <!-- Servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <!-- JSP -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

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

  <build>
    <plugins>
      <!-- tomcat插件 -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>8080</port>
          <path>/</path>
          <uriEncoding>UTF-8</uriEncoding>
          <server>tomcat7</server>
          <systemProperties>
            <java.util.logging.SimpleFormatter.format>%1$tH:%1$tM:%1$tS%2 $s%n%4$s: %5$s%6$s%n
            </java.util.logging.SimpleFormatter.format>
          </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

2.3 Modify the web.xml file 

        Then in the web.xml file under the WEB-INF directory under the resource webapp directory, this is the webapp core configuration file, and configure related content

<!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
        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>
  <!-- SpringMVC前端控制器,本质是一个Servlet,接受所有请求,在容器启动时就会加载 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 默认进入obj2Param.jsp页面 -->
  <welcome-file-list>
    <welcome-file>obj2Param.jsp</welcome-file>
  </welcome-file-list>

</web-app>

2.4 Create a new springmvc.xml file

        Write the SpringMVC core configuration file springmvc.xml, which is written in the same way as the Spring configuration file.

<?xml version="1.0" encoding="UTF-8" ?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描包 -->
    <context:component-scan base-package="com.example"/>
    <!-- 开启SpringMVC注解的支持 -->
    <mvc:annotation-driven/>
    
</beans>

2.5 Write the controller 

com.example.controller.MyController1.java controller file content:

package com.example.controller;

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

@Controller
public class MyController1 {
    // 该方法的访问路径是/c1/hello1

    @RequestMapping("/c/hello1")
    public void helloMCV(){
        System.out.println("hello springmvc");
    }
}

@Controller indicates that this is a control class

@RequestMapping shows that his context path is: /c/hello1

When running later, you can observe whether the console outputs hello springmvc 

2.6 Configure operation mode

Right click, as shown below 

Click the + sign, then select maven, and then select the project directory to run. The running command is: tomcat7:run

OK, click OK to complete the running configuration

2.7 Running tests 

Enter localhost:8080/c/hello1 in the URL bar and press Enter to run, you can see the following picture,

        In fact, it is normal to report 404 here, because here is a view to be returned, but I did not write this view, so I reported 404 not found, but observe whether the console output hello springmvc, if it is successfully printed out, it means that it is indeed running Success, as shown below 

Three, SpringMVC execution process

3.1 Components of SpringMVC

  1. DispatcherServlet: Front controller, accepts all requests and calls other components.
  2. HandlerMapping: The processor mapper, which finds the execution chain of the method according to the configuration.
  3. HandlerAdapter: Handler adapter, find the corresponding handler according to the method type.
  4. ViewResolver: view resolver, find the specified view.

3.2 Workflow of components

  1. The client sends the request to the front controller.
  2. The front controller sends the request to the processor mapper, and the processor mapper finds the execution chain of the method according to the path and returns it to the front controller.
  3. The front controller sends the execution chain of the method to the processor adapter, and the processor adapter finds the corresponding processor according to the method type.
  4. The handler executes the method, returning the result to the front controller.
  5. The front controller sends the result to the view resolver, and the view resolver finds the view file location.
  6. Views render data and display the results to the client.

Related readings of previous columns & articles 

     If you don’t know anything about the content of this issue, you can also go to the previous issues. The following is a series of column articles such as Maven and Mybatis carefully crafted by bloggers in the past. Don’t miss it when you pass by! If it is helpful to you, please like it and bookmark it. Among them, some of the Spring columns are being updated, so they cannot be viewed, but they can be viewed after the bloggers have completed all the updates.

1. Maven series of columns

Maven Series Column Maven project development
Maven aggregation development [example detailed explanation --- 5555 words]

2. Mybatis series of columns

Mybatis series column MyBatis entry configuration
Mybatis entry case [super detailed]
MyBatis configuration file - detailed explanation of related tags
Mybatis fuzzy query - three methods of defining parameters and aggregation query, primary key backfill
Mybatis dynamic SQL query -- (attached actual combat case -- 8888 words -- 88 quality points)
Mybatis paging query - four ways to pass parameters
Mybatis first level cache and second level cache (with test method)
Mybatis decomposition query
Mybatis related query [attached actual combat case]
MyBatis annotation development --- realize addition, deletion, modification and dynamic SQL
MyBatis annotation development --- realize custom mapping relationship and associated query

3. Spring series of columns 

Spring series column Introduction to getting started with Spring IOC [custom container instance]
IOC uses Spring to implement detailed explanation with examples
The creation method, strategy, destruction timing, life cycle and acquisition method of Spring IOC objects
Introduction to Spring DI and Dependency Injection Method and Dependency Injection Type
Application of Spring IOC-related annotations——Part 1
Application of Spring IOC-related annotations——Part 2
Introduction to Spring AOP and related cases
Annotation, native Spring, and SchemaBased implement AOP in three ways [with detailed case]
Introduction to Spring affairs and related cases
Spring transaction management scheme and transaction manager and transaction control API
Spring transaction related configuration, propagation behavior, isolation level and annotation configuration declarative transaction

4. Spring MVC series of columns 

SpringMVC series column Introduction to Spring MVC with an introductory case
Spring MVC various parameter acquisition and acquisition methods custom type converter and encoding filter
Spring MVC gets parameters and custom parameter type converters and encoding filters
Spring MVC processing response with detailed case explanation
Application of Spring MVC-related annotations—— Part 1

Application of Spring MVC-related annotations - Part 2

Application of Spring MVC-related annotations——Part 2
File upload in multiple situations of Spring MVC
Spring MVC asynchronous upload, cross-server upload and file download
Spring MVC exception handling [single control exception handler, global exception handler, custom exception handler]
Spring MVC interceptors and cross domain requests
SSM integration case [the case of station C explaining the most detailed process]

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/130274073