Spring MVC learning - Introduction and initial page construction

Posted by travelerBT on Sat, 19 Feb 2022 19:21:14 +0100

1, Introduction to spring MVC

1. What is MVC

MVC is an idea of software architecture, which divides software according to model, view and controller

M: Model, the model layer, refers to the JavaBean in the project, which is used to process data

JavaBean s fall into two categories:

  • One is called entity Bean: it is used to store business data, such as Student, User, etc
  • One is called business processing Bean: it refers to Service or Dao object, which is specially used to process business logic and data access.

5: V iew, the View layer, refers to pages such as html or jsp in the project. Its function is to interact with users and display data

C: Controller, the control layer, refers to the servlet in the project, which is used to receive requests and respond to browsers

MVC workflow:
The user sends a request to the server through the View layer, and the request is received by the Controller in the server. The Controller calls the corresponding Model layer to process the request, and returns the result to the Controller after processing. The Controller finds the corresponding View according to the request processing result, and finally responds to the browser after configuring the data

2. What is spring MVC

Spring MVC is a follow-up product of spring and a subproject of spring

Spring MVC is a complete set of solutions provided by spring for presentation layer development. After the evolution of many products such as struts, WebWork and strut2, the presentation layer framework has generally chosen spring MVC as the preferred scheme for the development of presentation layer of Java EE project.

Note: the three-tier architecture is divided into presentation layer (or presentation layer), business logic layer and data access layer. The presentation layer represents the foreground page and background servlet

3. Characteristics of spring MVC

  • The native products of Spring family are seamlessly connected with infrastructure such as IOC container
  • Based on the native Servlet, the powerful front-end controller dispatcher Servlet is used to process the request and response uniformly
  • The problems to be solved in each subdivided field of the presentation layer are covered in an all-round way to provide comprehensive solutions
  • The code is fresh and concise, which greatly improves the development efficiency
  • High degree of internal componentization, pluggable components plug and play, and you can configure the corresponding components according to the functions you want
  • Outstanding performance, especially suitable for modern large and super large Internet projects

2, HelloWorld

1. Development environment

IDE: idea 2020.2.4

Build tool: Maven 3 six point three

Server: tomcat9

Spring version: 5.3.1

2. Create maven project

a> Packing method: war

pom: used in parent project or aggregation project for version control of jar package. It must be indicated that the packaging method of this aggregation project is pom.

Jar: the default packaging method of the project. It is packaged into jar and used as a jar package. Store some classes and tools that will be used in other projects. We can refer to it in pom files of other projects

War: it will be packaged into war and published on the server, such as website or service. Users can access directly through the browser or be called by other projects through publishing services

b> Introduce dependency
<dependencies>
    <!-- SpringMVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.1</version>
    </dependency>

    <!-- journal -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>

    <!-- ServletAPI -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- Spring5 and Thymeleaf Integration package -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.12.RELEASE</version>
    </dependency>
</dependencies>

Note: due to Maven's transitivity, we do not need to configure all the required packages, but configure the top dependency, and others rely on transitive import.

c> Add web module

When adding a web module, the style of the web folder should take a small circle

If not, there may be a problem with maven. Click POM The refresh button in the upper right corner of the XML page can be refreshed


There may also be a problem with IDEA:

3. Configure web xml

Create a webapp folder in main under src of the current module. Then configure the web xml

Register the DispatcherServlet of the front-end controller of spring MVC

a> Default configuration method

Under this configuration, the configuration file of spring MVC is located under WEB-INF by default, and the default name is < servlet name > value - servlet XML, for example, the configuration file of spring MVC corresponding to the following configuration is located under WEB-INF, and the file name is SpringMVC-servlet xml

<!-- to configure SpringMVC The front-end controller of the browser uniformly processes the requests sent by the browser -->
<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!--
        set up springMVC The request path of the request that can be processed by the core controller of
        /The matching request can be/login or.html or.js or.css Mode request path
        however/Cannot match.jsp Request for request path
    -->
    <url-pattern>/</url-pattern>
</servlet-mapping>
b> Extended configuration mode

The location and name of the spring MVC configuration file can be set through the init param tag, and the initialization time of the spring MVC front-end controller DispatcherServlet can be set through the load on startup tag

<!-- to configure SpringMVC The front-end controller of the browser uniformly processes the requests sent by the browser -->
<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- Specified by initialization parameters SpringMVC Location and name of the configuration file -->
    <init-param>
        <!-- contextConfigLocation Is a fixed value -->
        <param-name>contextConfigLocation</param-name>
        <!-- use classpath:Indicates finding a configuration file from a classpath, for example maven In Engineering src/main/resources -->
        <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <!-- 
 		As the core component of the framework, there are a lot of initialization operations to be done during the startup process
		These operations are only executed when the first request is made, which will seriously affect the access speed
		Therefore, it is necessary to start the control through this label DispatcherServlet The initialization time of is advanced to the time when the server starts
	-->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!--
        set up springMVC The request path of the request that can be processed by the core controller of
        /The matching request can be/login or.html or.js or.css Mode request path
        however/Cannot match.jsp Request for request path
    -->
    <url-pattern>/</url-pattern>
</servlet-mapping>

Note:

Differences between / and / * in < URL pattern > Tags:

/The matching request can be / login or html or js or css request path, but / cannot match jsp request path

The corresponding page can be prevented from being accessed when the servlet cannot be found

/*It can match all requests. For example, when using filters, if you need to filter all requests, you need to use the writing method of / *

4. Create request controller

Because the front-end controller processes the requests sent by the browser uniformly, but the specific requests have different processing processes, it is necessary to create a class to process the specific requests, that is, the request controller

Each method in the request controller that processes the request becomes the controller method

Because the Controller of Spring MVC is a POJO (ordinary Java class), it needs to be identified as a control layer component through the @ Controller annotation and managed by Spring's IoC container. At this time, Spring MVC can recognize the existence of the Controller

@Controller
public class HelloController {
    
}

5. Create a configuration file for spring MVC

<!-- Automatic scanning package -->
<context:component-scan base-package="com.atguigu.mvc.controller"/>

<!-- to configure Thymeleaf view resolver  -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <property name="order" value="1"/>
    <property name="characterEncoding" value="UTF-8"/>
    <property name="templateEngine">
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
            <property name="templateResolver">
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    
                    <!-- View prefix -->
                    <property name="prefix" value="/WEB-INF/templates/"/>
    
                    <!-- View suffix -->
                    <property name="suffix" value=".html"/>
                    <property name="templateMode" value="HTML5"/>
                    <property name="characterEncoding" value="UTF-8" />
                </bean>
            </property>
        </bean>
    </property>
</bean>

<!-- 
   Processing static resources, such as html,js,css,jpg
  If only this tag is set, only static resources can be accessed, and other requests cannot be accessed
  It must be set at this time<mvc:annotation-driven/>solve the problem
 -->
<mvc:default-servlet-handler/>

<!-- open mvc Annotation driven -->
<mvc:annotation-driven>
    <mvc:message-converters>
        <!-- Processing response Chinese content garbled code -->
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="defaultCharset" value="UTF-8" />
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html</value>
                    <value>application/json</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

6. Test HelloWorld

a> Realize the access to the home page

Create a method to process the request in the request controller

// @RequestMapping annotation: handle the mapping relationship between the request and the controller method
// @The value attribute of the RequestMapping annotation can match the context path of the current project represented by / through the request address
// localhost:8080/springMVC/
@RequestMapping("/")
public String index() {
    //Set view name
    return "index";
}
b> Jump to the specified page through hyperlink

On the homepage index Set hyperlink in HTML

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>home page</title>
</head>
<body>
    <h1>home page</h1>
    <a th:href="@{/target}">HelloWorld</a><br/>
</body>
</html>

Create a method to process the request in the request controller

@RequestMapping("/target")
public String HelloWorld() {
    return "target";
}

7. Summary

The browser sends a request. If the request address conforms to the URL pattern of the front-end controller (the URL pattern is written as /, and everything can be matched except. jsp), the request will be processed by the front-end controller DispatcherServlet. The front-end controller will read the core configuration file of spring MVC, find the controller by scanning the component, and match the request address with the value attribute value of the @ RequestMapping annotation in the controller. If the matching is successful, the controller method identified by the annotation is the method of processing the request. The method of processing the request needs to return a view name of string type. The view name will be parsed by the view parser, plus prefix and suffix to form the path of the view. The view will be rendered through Thymeleaf, and finally forwarded to the page corresponding to the view

Topics: Java SSM mvc