It is enough to learn the integration of Spring and Web environment and the quick start of SpringMVC

Baojianfeng comes from the sharpening, and the fragrance of plum blossoms comes from bitter cold.
--mutual encouragement

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, newClasspathXmlApplicationContext (spring configuration file) must be written. The disadvantage of this is that the configuration
file is loaded many times, and the application context object is created many times. Second-rate.
In a web project, ServletContextListener can be used to monitor the startup of the web application. When the web application starts, we can load the Spring configuration file, 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 that 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 The user gets 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 get 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

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

SpringMVC

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 at present, 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.

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

① Import the coordinates of Spring and SpringMVC

<!--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>

① Import the coordinates of Servlet and Jsp

<!--Servlet坐标-->
 <dependency> 
 <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
   <version>2.5</version>
</dependency>
<!--Jsp坐标--> 
<dependency> 
<groupId>javax.servlet.jsp</groupId>
 <artifactId>jsp-api</artifactId>
  <version>2.0</version>
</dependency>

② 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>

③ Create Controller and business method

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

③ Create the view page index.jsp

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

④ Configuration Notes

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

⑤ 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>

SpringMVC process diagram

insert image description here

SpringMVC component resolution

The execution flow of SpringMVC

insert image description here
① 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 processor interceptor (if
any, generates) 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.

SpringMVC component analysis

  1. Front-end controller: DispatcherServlet
    user requests reach the front-end controller, which is equivalent to C in the MVC pattern. DispatcherServlet is the center of the entire process control, which calls other components to process user requests. The existence of DispatcherServlet reduces the coupling between components sex

  2. Handler mapper: HandlerMapping
    HandlerMapping is responsible for finding the Handler, that is, the handler according to the user's request. SpringMVC provides different mappers to implement different mapping methods, such as: configuration file method, implementation interface method, annotation method, etc.

  3. Handler adapter: HandlerAdapter
    executes the processor through HandlerAdapter, which is the application of the adapter mode, and more types of processors can be executed by extending the adapter.

  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 pass the processing result through The page is displayed to the user.

  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. In general, model data needs to be displayed to users through page tags or page template technology, and specific pages need to be developed by programmers according to business needs.

SpringMVC annotation parsing

@RequestMapping
role: used to establish the corresponding relationship between the request URL and the processing request method
Location:

  1. class, the first-level access directory for the request URL. If not written here, it is equivalent to the root directory of the application
  2. 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:

  1. value: The URL used to specify the request. It has the same function as the path attribute.
    2.method: used to specify the request method
    3.params: used to specify the conditions for limiting 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

mvc namespace introduction

命名空间:xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
约束地址: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

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" /> performs a component scan.

SpringMVC view resolver configuration

SpringMVC has default component configuration. The default components are configured in the DispatcherServlet.properties configuration file. The configuration file address is
org/springframework/web/servlet/DispatcherServlet.properties. The default view parser is configured in this file, as follows:

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

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>

Guess you like

Origin blog.csdn.net/JIAYOUYAA/article/details/124173328