Do you know the most popular SpringMVC framework at present? How should it be built?

Spring MVC (full name Spring Web MVC) is a lightweight Web development framework based on the MVC pattern provided by the Spring framework. It is a complete set of solutions provided by Spring for the development of the presentation layer (UI).

Note: The three-tier architecture is divided into presentation layer (UI), business logic layer (BLL), data access layer (DAL), and the presentation layer includes front page and background Servlet.

Spring MVC uses the idea of ​​MVC architecture pattern to deconstruct web applications and divide a complex web application into three layers: model (Model), controller (Contorller) and view (View), which effectively simplifies the development of web applications , which reduces the risk of errors and facilitates the division of labor among developers.

The responsibilities of each layer of Spring MVC are as follows:

  • Model: responsible for processing the request and returning the result to the Controller;
  • View: Responsible for rendering the processing results of the request and displaying them on the client browser;
  • Controller: It is the link between Model and View; it is mainly responsible for receiving user requests, calling Model to process the requests, and then passing the processing results of Model to View.

The essence of Spring MVC is a further encapsulation of Servlet. Its core component is DispatcherServlet, which is the front controller of Spring MVC and is mainly responsible for the unified processing and distribution of requests and responses. The request received by the Controller is actually distributed to it by the DispatcherServlet according to certain rules.

The Spring MVC framework uses a loosely coupled and pluggable component structure, which is highly configurable and more scalable and flexible than other MVC frameworks. In addition, Spring MVC's annotation-driven (annotation-driven) and support for REST style are also its most distinctive features.

Spring MVC is one of the many sub-projects of the Spring framework. It has been included in the Spring framework since the birth of the Spring framework. It can be seamlessly integrated with the Spring framework and has inherent advantages in performance. For developers, the development efficiency of Spring MVC is significantly higher than that of other web frameworks, so Spring MVC has been widely used in enterprises and has become one of the most mainstream MVC frameworks in the industry.

Common components of Spring MVC

Common components of Spring MVC are as follows:

components provider describe
DispatcherServlet framework provided The front controller, which is the entire Spring MVC process control center, is responsible for unified processing of requests and responses, and calls other components to process user requests.
HandlerMapping framework provided The handler mapper finds the corresponding Handler according to the requested url, method and other information.
Handler provided by the developer Processor, usually called Controller (controller). It can process specific user requests under the control of DispatcherServlet.
HandlerAdapter framework provided The processor adapter is responsible for invoking specific controller methods to process requests sent by users.
ViewResolver framework provided View parser, whose responsibility is to parse the view and get the corresponding view object. Common view resolvers include ThymeleafViewResolver, InternalResourceViewResolver, etc.
View provided by the developer View, its function is to display the model (Model) data to the user through the page.

Features of Spring MVC

Spring MVC has the following characteristics:

  • Spring MVC is a native product of the Spring family, which can seamlessly interface with Spring infrastructure such as IoC containers;
  • Spring MVC supports various view technologies such as JSP, Thymeleaf, JSP, and FreeMaker.
  • Spring MVC is based on the native Servlet implementation, and through the powerful front-end controller DispatcherServlet, requests and responses are processed in a unified manner;
  • Spring MVC covers all aspects of the problems that need to be solved in various subdivisions of the presentation layer, and provides a complete set of comprehensive solutions;
  • The code is fresh and concise, greatly improving development efficiency;
  • The degree of internal components is high, and the pluggable components are plug-and-play. If you want to use any function, you can configure the corresponding components;
  • Excellent performance, especially suitable for the development of modern large-scale and super-large Internet projects.

So how should we build the Spring MVC framework?

Including configuring the environment, creating projects, configuring frameworks, etc.

1. Environment configuration

Before starting, make sure you have completed the following environment configurations:

  1. Install the Java Development Kit (JDK): Make sure that the JDK has been installed on the computer, and the JAVA_HOME environment variable is correctly configured.
  2. Install Java development tools (IDE): You can choose Java development tools such as Eclipse and IntelliJ IDEA as the IDE.
  3. Download the Spring MVC framework: You can download the latest version of the Spring MVC framework from the Spring official website ( https://spring.io ).

2. Create a project

Next, we will create a new Java project to build the Spring MVC framework.

  1. Open the IDE, and create a new Java project.
  2. Create a folder called "lib" in the project to store the framework's JAR files.
  3. Copy the JAR file of the Spring MVC framework downloaded from the Spring official website into the "lib" folder.

3. Configuration framework

Now, we will configure the Spring MVC framework.

1. Create a folder named "WEB-INF" in the project to store the configuration files of the Web application.

2. Create a file called "web.xml" in the "WEB-INF" folder to configure Servlet and other web application settings. Here is an example of a basic "web.xml" file:

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

    <!-- 配置DispatcherServlet -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

</web-app>

In the above example, we configured a servlet called "springmvc" and mapped it to the root URL ("/"). We also contextConfigLocationspecified the Spring MVC configuration file location via parameters.

3. Create a file named "applicationContext.xml" in the "WEB-INF" folder to configure the relevant settings of the Spring MVC framework. Here is an example of a basic "applicationContext.xml" file:

<?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
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 启用Spring MVC注解驱动 -->
    <context:annotation-config/>
    <context:component-scan base-package="com.example"/>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

In the above example, we context:annotation-configenabled Spring MVC's annotation-driven, and specified context:component-scanthe base package that needs to be scanned. We also configured a view resolver InternalResourceViewResolverfor resolving JSP views.

4. Create a folder named "views" in the "WEB-INF" folder to store JSP view files.

4. Create Controller

Now, we will create a simple controller to handle user requests.

1. Create a package named "com.example" in the project.

2. Create a class named "HomeController.java" in the "com.example" package as our controller. Here is a basic controller example:

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView("home");
        modelAndView.addObject("message", "Hello, Spring MVC!");
        return modelAndView;
    }
}

In the above example, we @Controllermarked the class as a controller with an annotation. Through @RequestMappingthe annotation, we specify to handle the GET request of the root URL ("/") and return an ModelAndViewobject containing the view name and model data.

5. Create a view

Finally, we'll create a simple JSP view to display the response.

Create a file called "home.jsp" in the "views" folder. Here is an example of a basic JSP view:

<!DOCTYPE html>
<html>
<head>
    <title>Spring MVC Example</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

In the above example, we used ${message}to display the data passed from the controller.

6. Deploy and run

After completing the above steps, you can deploy and run the Spring MVC application as follows:

  1. Deploy the project to a web server (such as Tomcat). Package the entire project directory as a WAR file, and then deploy the WAR file to the webapps directory of the Web server.
  2. Start the web server. The startup command may differ depending on the Web server used.
  3. Access the application in a web browser. Use the URL http://localhost:8080/(according to the web server configuration) to access the root URL of the application.

HomeControllerThe method defined in will be triggered when the root URL of the application is accessed home(). This method will return the "home" view and pass "Hello, Spring MVC!" as model data to the view. The view will display the message.

Through the above steps, a simple Spring MVC framework has been successfully built, and a controller and view for processing requests and displaying responses have been created.

It should be noted that the above is just a basic Spring MVC framework construction process. In practical applications, more configurations and functions may be involved, such as data persistence, form processing, interceptors, etc. Spring MVC provides rich functions and extension points to build complex web applications.

Dark Horse Programmer SSM Framework Tutorial_Spring+SpringMVC+Maven Advanced+SpringBoot+MyBatisPlus Enterprise Practical Development Technology

Guess you like

Origin blog.csdn.net/Itmastergo/article/details/132017062