ishowcode.eth

ishowcode.eth

区块链小白

Springmvc Basics

SpringMVC Basics#

  • [Application] Able to independently complete a SpringMVC introductory case
  • [Application] Able to describe the execution process of SpringMVC
  • [Application] Able to be familiar with commonly used components of SpringMVC

1. Introduction to SpringMVC#

1.1 Overview of SpringMVC#

SpringMVC is a lightweight web framework based on Java that implements the MVC design model in a request-driven manner. It is a subsequent product of the Spring Framework and has been integrated into Spring Web Flow.

SpringMVC has become one of the most mainstream MVC frameworks, and with the release of Spring 3.0, it has fully surpassed Struts2, becoming the best MVC framework. It allows a simple Java class to become a controller that handles requests through a set of annotations, without the need to implement any interfaces. It also supports RESTful programming style requests.

1.2 SpringMVC Processing Flow#

Insert image description here

1.3 Quick Start with SpringMVC#

Requirement: The client initiates a request, the server receives the request, executes logic, and performs a view jump.

Development Steps

① Import SpringMVC related dependencies
② Configure the core controller DispatcherServlet of SpringMVC
③ Create Controller classes and view pages
④ Use annotations to configure the mapping addresses of business methods in the Controller class
⑤ Configure the core file of SpringMVC spring-mvc.xml
⑥ Client initiates request testing

Code Implementation
① Import dependencies for Spring and SpringMVC, and import dependencies for Servlet and JSP

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐test</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐tx</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!-- SpringMVC related -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐web</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!-- Data source related -->
<!-- Druid connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- MySQL driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql‐connector‐java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- Servlet related -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet‐api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp‐api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

② Configure the core controller of SpringMVC in web.xml

<!-- Configure the SpringMVC front controller -->
<servlet>
<servlet‐name>springmvc</servlet‐name>
<servlet‐class>org.springframework.web.servlet.DispatcherServlet</servlet‐class>
<!-- Load SpringMVC configuration file -->
<init‐param>
<param‐name>contextConfigLocation</param‐name>
<param‐value>classpath:spring‐mvc.xml</param‐value>
</init‐param>
<load‐on‐startup>1</load‐on‐startup>
</servlet>
<servlet‐mapping>
<servlet‐name>springmvc</servlet‐name>
<!--
*.action only processes requests with the .action suffix
/* intercepts all requests including static resources like JSP
/ intercepts all requests except JSP, it is recommended to configure /
-->
<url‐pattern>/</url‐pattern>
</servlet‐mapping>

③ Create Controller and business methods

@Controller
public class UserController {
@RequestMapping("/quick")
public String list(){
System.out.println("I executed");
return "success.jsp";
}
}

③ Create view page success.jsp

<%@ page contentType="text/html;charset=UTF‐8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>hello, springmvc!!</h1>
</body>
</html>

④ Configure annotations

@Controller
public class UserController {
@RequestMapping("/quick")
public String list(){
System.out.println("I executed");
return "success.jsp";
}
}

⑤ Create spring-mvc.xml

<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">
<!-- Configure annotation scanning -->
<context:component‐scan base‐package="com.bailiban.controller"/>
</beans>

⑥ Access test address

http://localhost:8080/quick

Console output

Insert image description here

Page display

Insert image description here

1.4 Key Points#

Development steps of SpringMVC
① Import SpringMVC related dependencies
② Configure the core controller DispatcherServlet of SpringMVC
③ Create Controller classes and view pages
④ Use annotations to configure the mapping addresses of business methods in the Controller class
⑤ Configure the core file of SpringMVC spring-mvc.xml
⑥ Client initiates request testing

2. Component Analysis of SpringMVC#

2.1 Execution Process of SpringMVC#

Insert image description here

① The user sends a request to the front controller DispatcherServlet.
② DispatcherServlet receives the request and calls the HandlerMapping processor mapper.
③ The processor mapper finds the specific handler (which can be found based on XML configuration, annotations, etc.), generates the handler object and handler interceptor (if any) and returns them to DispatcherServlet.
④ DispatcherServlet calls the HandlerAdapter processor adapter.
⑤ HandlerAdapter adapts and calls the specific handler (Controller, also called the backend controller).
⑥ The Controller completes execution and returns ModelAndView.
⑦ HandlerAdapter returns the execution result ModelAndView from the controller to DispatcherServlet.
⑧ DispatcherServlet passes ModelAndView to the ViewResolver view resolver.
⑨ ViewResolver parses and returns the specific View.
⑩ DispatcherServlet renders the view based on the View (i.e., fills the model data into the view). DispatcherServlet responds to the user.

2.2 Component Analysis of SpringMVC#

  1. Front Controller: DispatcherServlet

    The user request reaches the front controller, which acts as the C in the MVC pattern. DispatcherServlet is the control center of the entire process, calling other components to handle user requests, reducing the coupling between components.

  2. Handler Mapper: HandlerMapping

    HandlerMapping is responsible for finding the Handler (i.e., handler) based on user requests. SpringMVC provides different mappers to implement different mapping methods, such as configuration file method, interface implementation method, annotation method, etc.

  3. Handler Adapter: HandlerAdapter

    The HandlerAdapter executes the handler, applying the adapter pattern. By extending the adapter, more types of handlers can be executed.

  4. Handler: Handler

    This is the specific business controller that we need to write in development. The DispatcherServlet forwards user requests to the Handler, which processes the specific user requests.

  5. View Resolver: View Resolver

    The View Resolver is responsible for generating the View from the processing result. It first resolves the logical view name into a physical view name, i.e., the specific page address, then generates the View object, and finally renders the View to display the processing result to the user.

  6. View: View

    The SpringMVC framework provides support for many types of View, including jstlView, freemarkerView, pdfView, etc. The most commonly used view is JSP. Generally, it is necessary to use page tags or page template technologies to display model data to users through pages, which requires programmers to develop specific pages according to business needs.

Note: Among the various components of SpringMVC, the handler mapper, handler adapter, and view resolver are referred to as the three major components of SpringMVC. The components that need to be developed by the user are handler and view.

2.3 Default Loaded Components#

We can use these components without any configuration because the framework has already loaded them by default. The configuration file location is shown in the image below:

Insert image description here

2.4 Annotation Driven#

Directly configuring the handler mapper and handler adapter can be cumbersome, so annotation-driven loading can be used.

SpringMVC uses

<!-- Annotation driven -->
<mvc:annotation‐driven />

Automatically loads RequestMappingHandlerMapping and RequestMappingHandlerAdapter which can be used in the springmvc.xml configuration file with <mvc:annotation-driven /> to replace the default configuration of the annotation handler and adapter.

2.5 Configuration of SpringMVC View Resolver#

SpringMVC has default component configurations, and the default components are configured in the DispatcherServlet.properties configuration file, which includes the default view resolver as follows:

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

Looking at the source code of this resolver, we can see its default settings as follows:

REDIRECT_URL_PREFIX = "redirect:" -- Redirect prefix
FORWARD_URL_PREFIX = "forward:" -- Forward prefix (default value)
prefix = ""; -- View name prefix
suffix = ""; -- View name suffix

In development, we generally place views in the WEB-INF directory and can modify the prefix and suffix of the view through property injection for easier development.

<!-- Configure view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB‐INF/jsp/" ></property>
<property name="suffix" value=".jsp"></property>
</bean>

2.6 SpringMVC Annotation Parsing#

@RequestMapping

Function: Used to establish the correspondence between request URLs and request handling methods
Location:
On the class, it represents the first-level access directory of the request URL. If not specified, it is equivalent to the root directory of the application.
On the method, it represents the second-level access directory of the request URL, which, together with the first-level directory marked with @RequestMapping on the class, forms the access virtual path.
Attributes:
value: Used to specify the request URL. It has the same function as the path attribute.
method: Used to specify the request method.
params: Used to specify conditions that restrict request parameters. It supports simple expressions. The key and value of the request parameters must match exactly with the configuration.
For example:

params = {"accountName"}, indicates that the request parameter must have accountName.
params = {"money!100"}, indicates that the request parameter money cannot be 100.

2.7 Key Points#

Components related to SpringMVC

Front Controller: DispatcherServlet
Handler Mapper: HandlerMapping
Handler Adapter: HandlerAdapter
Handler: Handler
View Resolver: ViewResolver
View: View

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.