【SpringMVC】| Getting Started with SpringMVC

Table of contents

One: Getting Started with SpringMVC

1. Introduction to Spring MVC

2. Advantages of Spring MVC

3. Optimization of Spring MVC

4. The process of SpringMVC execution

5. Annotation-based SpringMVC program

book recommendation

One: "Spring Boot Advanced: Principles, Practice and Analysis of Interview Questions"

Two: "In-depth understanding of Java virtual machine"


One: Getting Started with SpringMVC

1. Introduction to Spring MVC

(1) First of all, let's recall the three-tier architecture of MVC?
It is a development model, which is the abbreviation of model, view and controller; all web applications are developed based on MVC.
M: Model layer, including entity classes, business logic layer, and data access layer.
V: View layer, html, javaScript, vue, etc. are all view layers, used to display data.
C: The controller, which is used to receive the client's request and return the response to the client's component, Servlet is the component.

(2) What is Spring MVC?
It is a framework based on the MVC development model to optimize controllers . It is a member of the Spring family; it also has IOC and AOP.

(3) The optimization direction of the SSM framework?

MyBatis is used to optimize the data access layer (persistence layer framework) .

SpringMVC is used to optimize the control machine , for example: Servlet.

Spring is used to integrate other frameworks .

2. Advantages of Spring MVC

(1) Based on MVC architecture

Based on the MVC architecture, the functional division of labor is clear; decoupling.

(2) Easy to understand, quick to use and easy to use

An annotated SpringMVC project can be developed. SpringMVC is also lightweight, and the jar is small; it does not depend on specific interfaces and classes.

(3) Possess IOC and AOP

It is convenient to integrate other frameworks such as Strtus, MyBatis, Hiberate, etc.

(4) Strengthen the use of annotations (full annotation development)

Annotations can be used in Controller, Service, and Dao, which is convenient and flexible. Use @Controller to create processor objects, @Service to create business objects, @Autowired or @Resource to inject Service into the controller class, and inject Dao into the Service class.

3. Optimization of Spring MVC

(1) The user sends a request to the Tomcat server first , and then checks the web.xml configuration ; if SpringMVC is configured in it, the control is handed over to the framework .

(2) SpringMVC calls the controller Controller to optimize the data submitted by the client, optimize the data carried, and optimize the return jump.

(3) Then the controller calls the business logic layer, and the business logic layer calls the data access layer; then the data access layer connects to the database, and finally returns the data.

4. The process of SpringMVC execution

(1) The client sends an HTTP request to the server, and the request is captured by the pre-controller DispatcherServlet (the core processor of the SpringMVC framework) .

(2) DispatcherServlet (front controller) [Hero] Analyze the requested URL according to the configuration in <servlet-name>, and obtain the requested resource identifier (URI) . Then according to the URI, call HandlerMapping (address mapper) [the first small helper] to obtain all related objects configured by the Handler (including the Handler object and the interceptor corresponding to the Handler object), and finally return it in the form of a HandlerExecutionChain object.

(3) DispatcherServlet selects an appropriate HandlerAdapter (adapter) [the second little helper] according to the obtained Handler , and then calls the business logic layer, data access layer, and finally a ModelAndView object .

(4) Analysis: Extract the model data in the Request, fill in the Handler input parameters, and start executing the Handler. In the process of filling Handler's input parameters, according to your configuration, Spring will help you do some extra work:

HttpMessageConveter: Convert request messages (such as Json, xml, etc.) into an object, and convert the object into specified response information.

①Data conversion: perform data conversion on the request message; such as converting String to Integer, Double, etc.

②Data formatting: data formatting for request messages; such as converting strings into formatted numbers or formatted dates, etc.

③Data verification: verify the validity of the data (length, format, etc.), and store the verification results in BindingResult or Error

After the Handler is executed, it returns a ModelAndView object to the DispatcherServlet.

(5) According to the returned ModelAndView , select a suitable ViewResolver (the view resolver must be a ViewResolver that has been registered in the Spring container) [the third little helper] , which is mainly used to return the client request address splicing, divided into The prefix part and suffix part are finally returned to DispatcherServlet .

(6) ViewResolver combines Model and View to render the view; the view is responsible for returning the rendering result to the client.

5. Annotation-based SpringMVC program

Step 1: Create a new project and select the webapp template

Step 2: Modify the directory, add the missing test, java, resources (two sets), and modify the directory properties

Step 3: Modify the pom.xml file, add SpringMVC dependencies, and add Servlet dependencies

For the parsing of the last specified resource file:

By default, maven will package or publish all configuration files under src/main/resources and all java files under src/main/java to target\classes ; we may also place some configuration files under src/main/java such as : xxx.xml configuration, xxx.properties configuration; if we do not do some additional configuration, then our packaged project may not find these necessary resource files!

<?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.bjpowernode</groupId>
  <artifactId>SpringMVC-001</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringMVC-001 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</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>
  </properties>

  <dependencies>
    <!--添加SpringMVC依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--添加Servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <!--指定资源文件-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

Step 4: Add springmvc.xml configuration file : specify package scan, add view parser

Use InternalResourceViewResolver (internal resource view resolver) , specify the prefix and suffix of the resource!

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置包扫描-->
    <context:component-scan base-package="com.bjpowernode.controller"/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/admin/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

The role of the view parser configuration is to jump to the page, jump to the /admin/xxx.jsp page, here it is assumed to jump to the main.jsp file, you need to create an admin directory first, and then create a mian in the directory. jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>main.........</h1>
</body>
</html>

Step 5: Delete the web.xml file (lower version), create a new web.xml; and register the springMVC framework in the web.xml file

Note: We know that all web requests are based on servlets, but SpringMVC's processor itself is a common method; so the core processor DispatcherServlet is required, and DispatcherServlet must be registered in the web.xml file before it can be used!

①Add initialization configuration: Specify what kind of requests DispactherServlet should intercept?

②Introduce springmvc.xml configuration: use contextConfigLocation as name, classpath:springmvc.xml as value to introduce springmvc.xml configuration, and tell DispatchServlet to process it!

<?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">
    <!--注册SpringMVC框架-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--引入springmvc的核心配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--指定拦截什么样的请求
            例如:http://localhost:8080/demo.action
        -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

Step 6: Delete the index.jsp page (non-compliant), create a new one, and send the request to the server

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--发送请求--%>
<a href="${pageContext.request.contextPath}/demo.action">访问服务器</a>
</body>
</html>

Step 7: Create a processor action similar to the Servlet function

Analysis: The previous Servlet specification, protected void doPost

(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} must be this form of
action. All functions in the action are implemented by the method. The specification of the action method:
①The access right is public;
②The return value of the method is arbitrary ;
③The name of the method is arbitrary;
④The method can have no parameters, if there is, it can be of any type;
⑤Use the @RequestMapping annotation to declare an access path (name);

Note: If springMVC is not used, there is no difference between @Controller annotation and @Service, @Component, @Repository annotation, but if springMVC is used, @Controller is given a special meaning! Spring will traverse all the beans scanned above, filter out those beans that have been annotated with @Controller, parse all the methods in the Controller that have been annotated with @RequestMapping, encapsulate them into RequestMappingInfo and store them in the mappingRegistry in RequestMappingHandlerMapping . When subsequent requests arrive, the mappingRegistry is looked up for a method that can handle the request.

package com.bjpowernode.controller;

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

@Controller // 交给spring容器去创建对象
public class DemoAction {
    /**
     * 1)访问权限是public
     * 2)方法的返回值任意
     * 3)方法名称任意
     * 4)方法可以没有参数,如果有可是任意类型
     * 5)要使用@RequestMapping注解来声明一个访问的路径(名称)
     */
    @RequestMapping("/demo")
    public String demo(){
        System.out.println("服务器被访问到了......");
        // 根据返回的main,就可以跳转到/admin/main.jsp页面上
        return "main";
    }
}

Step Eight: Test

The first thing to visit is index.jsp. When clicking on the hyperlink, it will jump to DemoAction (similar to the function of Servlet), and then return a "main" string

According to the returned string "mian", the core processor DispatcherServlet will complete the path splicing according to the view parser in the registered springmvc.xml file: add prefix and suffix: /admin/main.jsp, and finally complete the page jump change

book recommendation

Books in this issue: "Advanced Spring Boot: Principles, Practice and Analysis of Interview Questions", "In-depth Understanding of Java Virtual Machines"

way of participation:

One book is tentatively scheduled for this time (choose one from two), and one more book will be given if more than 1,000 pageviews are received! 
Activity time: until 2023-04-29 00:00:00.

Lottery draw method: Use the program to draw a lottery.

Participation method: follow the blogger (only for fan benefits), like, bookmark, random selection in the comment area, up to three comments!

One: "Spring Boot Advanced: Principles, Practice and Analysis of Interview Questions"

Recommended reason: Spring Boot has become a technology that Java programmers have to learn. This book covers the core technical points of Spring Boot, gradually transitioning from basic concepts to technical principles and interview points that need to be focused on, helping readers quickly learn to use Spring Boot and master Spring Boot technical principles and solutions.

Interested partners can learn more through the link below: Inventory of classic books not to be missed in 2022: Java Development 

Two: "In-depth understanding of Java virtual machine"

Reason for recommendation: "In-depth Understanding of Java Virtual Machine" written by Mr. Zhou Zhiming has helped hundreds of thousands of Java development engineers and architects in China to deepen their understanding of JVM. Elementary interview questions. This great factory interview clearance book comprehensively analyzes virtual machines from five dimensions: Java technology system, automatic memory management, virtual machine execution subsystem, program compilation and code optimization, and efficient concurrency. Guided by actual combat, through a large number of practical cases, share solutions and techniques for solving various Java technical problems. Covers almost all the knowledge points of interviews in big factories. It is worth reading again and again for all Java technicians.

Interested partners can find out through the link below:   Java will celebrate its 27th birthday!

Guess you like

Origin blog.csdn.net/m0_61933976/article/details/128796992