[SSM hits the big factory directly] Chapter 4: SpringMVC Quick Start

content

1. Spring integrated web environment

1.1 ApplicationContext Application context acquisition method

1.2 Spring provides tools to obtain application context

1.3 Import the coordinates of the Spring integrated web

1.4 Configure the ContextLoaderListener listener

1.5 Obtaining application context objects through tools

1.6 Key points of knowledge

2. Introduction to SpringMVC

2.1 Overview of SpringMVC

 2.2 SpringMVC Quick Start

2.3 SpringMVC process diagram

2.4 Key points of knowledge

3. SpringMVC component resolution

3.1 Execution process of SpringMVC

3.2 SpringMVC component analysis

3.3 SpringMVC annotation analysis

3.4 XML configuration parsing of SpringMVC

3.5 Key points of knowledge


1. Spring integrated web environment

1.1 ApplicationContext Application context acquisition method

The application context object is obtained through new ClasspathXmlApplicationContext (spring configuration file), but every time a bean is obtained from the container, new ClasspathXmlApplicationContext (spring configuration file) must be written. The disadvantage of this is that the configuration file is loaded multiple times and the application context object is created. repeatedly.
In a web project, the ServletContextListener can be made to monitor the startup of the web application. We can load the Spring configuration file when the web application starts, create the application context object ApplicationContext, and store it in the largest domain servletContext domain, so that we can Get the application context ApplicationContext object from the domain anywhere.

1.2 Spring provides tools to obtain application context

The above analysis does not need to be implemented manually . Spring provides a listener, ContextLoaderListener, which encapsulates the above functions. The listener loads Spring configuration files, creates application context objects, and stores them in the ServletContext domain. A client tool, WebApplicationContextUtils, is provided for use. The user obtains the application context object.
So there are only two things we need to do :
① Configure the ContextLoaderListener listener in web.xml (import spring-web coordinates).
② Use WebApplicationContextUtils to obtain the application context object ApplicationContext.

1.3 Import the coordinates of the Spring integrated web

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>5.0.5.RELEASE</version>
</dependency>

1.4 Configure the ContextLoaderListener listener

<!--全局参数--> 
<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--Spring的监听器--> 
<listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
</listener>

1.5 Obtaining application context objects through tools

//java
ApplicationContext applicationContext = 
    WebApplicationContextUtils.getWebApplicationContext(servletContext);
Object obj = applicationContext.getBean("id");

1.6 Key points of knowledge

Spring integrated web environment steps
① Configure the ContextLoaderListener listener
② Use WebApplicationContextUtils to obtain the application context

2. Introduction to SpringMVC

2.1 Overview of SpringMVC

SpringMVC is a request-driven lightweight Web framework based on Java that implements the MVC design model. It is
a follow-up product of SpringFrameWork and has been integrated into Spring Web Flow.
SpringMVC has become one of the most mainstream MVC frameworks, and with the release of Spring3.0, it has surpassed Struts2 in an all-round way and become the best MVC framework. It uses a set of annotations to make a simple Java class a controller for handling requests without having to implement any interface. It also supports RESTful programming style requests.

 2.2 SpringMVC Quick Start

Requirement: The client initiates the request, the server receives the request, executes the logic and performs a view jump.
Development steps:
① Import SpringMVC-related coordinates
② Configure SpringMVC core controller DispathcerServlet
③ Create Controller class and view page
④ Use annotations to configure the mapping address of business methods in Controller class
⑤ Configure SpringMVC core file spring-mvc.xml
⑥ Client initiates request test

Code display:

1. Import SpringMVC related coordinates

<!--Spring坐标--> 
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>5.0.5.RELEASE</version>
</dependency>
<!--SpringMVC坐标--> 
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>5.0.5.RELEASE</version>
</dependency>

2. Configure the core controller of SpringMVC in web.xml

<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:spring-mvc.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>

3. Create Controller and Business Methods

public class QuickController {
    public String quickMethod(){
        System.out.println("quickMethod running.....");
        return "index";
     }
}

4. Create the view page index.jsp

<html>
 <body>
    <h2>Hello SpringMVC!</h2>
 </body>
</html>

5. Configuration annotations

@Controller
public class QuickController {
    @RequestMapping("/quick")
    public String quickMethod(){
        System.out.println("quickMethod running.....");
        return "index"; 
    } 
}

6. 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">
<!--配置注解扫描--> <context:component-scan base-package="com.itheima"/>
</beans>

7. Visit the test address

http://localhost:8080/project/quick

2.3 SpringMVC process diagram

2.4 Key points of knowledge

Development steps of SpringMVC

① Import SpringMVC-related coordinates
② Configure the SpringMVC core controller DispathcerServlet
③ Create Controller class and view page
④ Use annotations to configure the mapping address of business methods in the Controller class
⑤ Configure the SpringMVC core file spring-mvc.xml
⑥ Client initiates request test

3. SpringMVC component resolution

3.1 Execution process of SpringMVC

① The user sends a request to the front-end controller DispatcherServlet.
② DispatcherServlet receives the request and calls the HandlerMapping processor mapper.
③ The processor mapper finds a specific processor (which can be searched according to xml configuration and annotations), generates a processor object and a processing interceptor (if any) and returns it to DispatcherServlet.
④ DispatcherServlet calls HandlerAdapter processor adapter.
⑤ HandlerAdapter is adapted to call a specific processor (Controller, also called a back-end controller).
⑥ Controller execution completes and returns to ModelAndView.
⑦ HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet.
⑧ DispatcherServlet passes ModelAndView to ViewReslover view resolver.
⑨ ViewReslover returns the specific View after parsing.
⑩ DispatcherServlet renders the view according to the View (that is, fills the model data into the view). The DispatcherServlet responds to the user.

 3.2 SpringMVC component analysis

1. Front Controller: DispatcherServlet
When the user request reaches the front controller, it is equivalent to C in the MVC pattern. DispatcherServlet is the center of the entire process control, which calls other components to process the user's request. The existence of DispatcherServlet reduces the coupling between components.
2. Handler Mapper: HandlerMapping
HandlerMapping is responsible for finding Handlers or processors according to user requests. SpringMVC provides different mappers to implement different mapping methods, such as configuration file methods, interface implementation methods, annotation methods, etc.
3. Handler Adapter: HandlerAdapter
The processor is executed through HandlerAdapter, which is the application of the adapter mode, and more types of processors .
4. Handler: Handler
It is the specific business controller to be written in our development. The user request is forwarded to the Handler by the DispatcherServlet. Handler handles specific user requests.
5. View resolver: View Resolver
The View Resolver is responsible for generating the View view from the processing result. The View Resolver first resolves the logical view name into the physical view name, that is, the specific page address, then generates the View view object, and finally renders the View to display the processing result to the user through the page.
6. View: View
The SpringMVC framework provides support for many types of View views, including: jstlView, freemarkerView, pdfView, etc. The most commonly used view is jsp. Under normal circumstances, it is necessary to display model data to users through page tags or page template technology, and programmers need to develop specific pages according to business requirements.

3.3 SpringMVC annotation analysis

@RequestMapping
Role: used to establish the corresponding relationship between the request URL and the processing request method
Location:
  • class, the first-level access directory for the request URL. If not written here, it is equivalent to the root directory of the application
  • In terms of method, the second-level access directory of the request URL is combined with the first-level directory marked with @ReqquestMapping on the class to form an access virtual path
    Attributes:
  • value : Used to specify the requested URL. It has the same effect as the path attribute
  •  method : used to specify the method of the request
  • params : Used to specify conditions to limit request parameters. It supports simple expressions. It is required that the key and value of the request parameter must be exactly the same as the configuration
    For example: params = {"accountName"} , indicating that the request parameter must have accountName params = {"moeny!100"} , indicating that the money in the request parameter cannot be 100  
1. The introduction of mvc namespace
Namespaces:
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
Constraint address:
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
2. Component Scan
SpringMVC is based on the Spring container, so when performing SpringMVC operations, you need to store the Controller in the Spring container. If you use the @Controller annotation, you need to use < context :component-scan base
package ="com.itheima.controller" /> does a component scan.

3.4 XML configuration parsing of SpringMVC

view resolver

SpringMVC has default component configuration, the default components are configured in the DispatcherServlet.properties configuration file, the configuration file address
org/springframework/web/servlet/DispatcherServlet.properties , the default view resolver is configured in this file, as follows:
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.I
nternalResourceViewResolver
Looking at the source code of the parser, you can see the default settings of the parser, as follows:
REDIRECT_URL_PREFIX = "redirect:" --重定向前缀
FORWARD_URL_PREFIX = "forward:" --转发前缀(默认值)
prefix = ""; --视图名称前缀
suffix = ""; --视图名称后缀
We can modify the prefix and suffix of the view through property injection
<!--配置内部资源视图解析器--> 
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property>
</bean>

3.5 Key points of knowledge

Related components of SpringMVC
• Front Controller: DispatcherServlet
• Handler Mapper: HandlerMapping
• Handler Adapter: HandlerAdapter
• Handler: Handler
• View Resolver: View Resolver
• View: View
SpringMVC annotation and configuration
• Request mapping annotation: @RequestMapping
• View resolver configuration:
  REDIRECT_URL_PREFIX = "redirect:"
  FORWARD_URL_PREFIX = "forward:"
  prefix = "";
  suffix = "";

Guess you like

Origin blog.csdn.net/qq_52360069/article/details/123637714