Integration of Spring and Web Environment

1. Integration of spring and Web Environment

1.1 ApplicationContext application context acquisition method

The application context object is obtained through the new ClasspathXmlApplicationContext(spring configuration file), but each time a Bean is obtained from the container, the new ClasspathXmlApplicationContext(spring configuration file) must be written. This disadvantage is that the configuration file is loaded multiple times and the application context object is created multiple times.

In the Web project, you can use the ServletContextListener to listen to the start 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 the application context ApplicationContext object can be obtained from the domain at any location.

1.2 Spring provides tools for obtaining application context

The above analysis does not need to be implemented manually. Spring provides a listener, ContextLoaderListener, which encapsulates the above functions. The listener internally loads the spring configuration file, creates the application context object, and stores it in the ServletContext domain. It provides a client tool WebApplicationContextUtils for users to obtain 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)

② Get the application context object ApplicationContext using WebApplicationContextUtils

1.3 coordinates of importing Spring integrated web

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

1.4 configuring the ContextLoaderListener listener

<!--Global parameters-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--Spring Monitor for-->
<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");

Key points of knowledge

Steps to integrate the Spring web Environment

① configure the ContextLoaderListener listener

② use WebApplicationContextUtils to obtain the application context

2. Introduction to spring MVC

2.1 spring MVC overview

Spring MVC is a request driven lightweight Web framework based on Java to implement MVC design model. It is a follow-up product of spring framework and has been integrated into Spring Web Flow.

Spring MVC has become one of the most mainstream MVC frameworks, and with the release of spring 3.0, it has comprehensively surpassed struts 2 and become the best MVC framework. Through a set of annotations, it makes a simple Java class a controller for processing requests without implementing any interface. It also supports RESTful programming style requests.

2.3 spring MVC quick start

Requirements: the client initiates the request, the server receives the request, executes logic and jumps the view.

Development steps

① Import spring MVC related coordinates

② Configuring the spring MVC core controller DispathcerServlet

③ Create Controller classes and view pages

④ Use the annotation to configure the mapping address of the business method in the Controller class

⑤ Configure spring MVC core file spring-mvc.xml

⑥ Client initiated request test

code implementation

① Import the coordinates of Spring and Spring MVC, and import the coordinates of Servlet and Jsp

 <!--Spring coordinate-->
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>5.0.5.RELEASE</version>
 </dependency>
 <!--SpringMVC coordinate-->
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>5.0.5.RELEASE</version>
 </dependency>
<!--Servlet coordinate-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>
<!--Jsp coordinate-->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
</dependency>

② Configuring the core controller of spring MVC 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 view page index.jsp

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

④ Configuration annotation

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

⑥ Access test address

http://localhost:8080/itheima_springmvc1/quick 

Console printing

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-5x1dwAc5-1630656943092)(./img / picture 1.png)]

Page display

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-RYfHalzc-1630656943102)(./img / picture 2.png)]

2.3 spring MVC process diagram

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9keCA01S-1630656943106)(./img / picture 3.png)]

2.4 key points of knowledge

Development steps of spring MVC

① Import spring MVC related coordinates

② Configuring the spring MVC core controller DispathcerServlet

③ Create Controller classes and view pages

④ Use the annotation to configure the mapping address of the business method in the Controller class

⑤ Configure spring MVC core file spring-mvc.xml

⑥ Client initiated request test

3. Component parsing of spring MVC

3.1 execution process of spring MVC

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-DFRQOXIv-1630656943114)(./img / picture 4.png)]

① The user sends a request to the front-end controller DispatcherServlet.

② The dispatcher servlet receives a request to call the handler mapping processor mapper.

③ The processor mapper finds the specific processor (which can be found according to the xml configuration and annotation), generates the processor object and the processor interceptor (if any) and returns it to the dispatcher servlet.

④ Dispatcher servlet calls HandlerAdapter processor adapter.

⑤ The HandlerAdapter invokes a specific processor (Controller, also known as back-end Controller) through adaptation.

⑥ The Controller returns ModelAndView after execution.

⑦ The HandlerAdapter returns the controller execution result ModelAndView to the dispatcher servlet.

⑧ The dispatcher servlet passes the ModelAndView to the viewrestrover view parser.

⑨ The viewrestrover returns the specific View after parsing.

⑩ The dispatcher servlet renders the View according to the View (that is, fills the View with model data). Dispatcher servlet responds to the user.

3.2 spring MVC component parsing

  1. Front end controller: dispatcher Servlet

When the user requests to reach the front-end controller, it is equivalent to C in MVC mode. The dispatcher servlet is the center of the whole process control

It calls other components to process user requests. The existence of dispatcher servlet reduces the coupling between components.

  1. Processor mapper: HandlerMapping

HandlerMapping is responsible for finding the Handler, that is, the processor, according to the user's request. Spring MVC provides different mappers to implement different functions

Mapping mode, such as configuration file mode, implementation interface mode, annotation mode, etc.

  1. Processor adapter: HandlerAdapter

The processor is executed through the HandlerAdapter, which is an application of adapter mode. More types of processing can be performed through the extension adapter

The actuator.

  1. Processor: Handler

It is the specific business controller to be written in our development. The dispatcher servlet forwards the user request to the Handler. from

Handler handles specific user requests.

  1. View Resolver: View Resolver

The View Resolver is responsible for generating the processing results into the View view. The View Resolver first resolves the logical View name into the physical View name, that is, the specific page address, and then generates the View object. Finally, it renders the View and displays the processing results to the user through the page.

  1. Views: View

Spring MVC framework provides support for many View types, including jstlView, freemarkerView, pdfView, etc. The most common View is jsp. Generally, the model data needs to be displayed to users through pages through page label or page template technology. Programmers need to develop specific pages according to business requirements

3.3 spring MVC annotation parsing

@RequestMapping

Function: used to establish the correspondence between the request URL and the request processing method

Location:

Class, request the first level access directory of the URL. If it is not written here, it is equivalent to the root directory of the application

Method, the second level access directory of the request URL and the first level directory marked with @ ReqquestMapping on the class form an access virtual path

Properties:

value: used to specify the URL of the request. It works the same way as the path attribute

Method: used to specify the method of the request

params: used to specify conditions that restrict request parameters. It supports simple expressions. key and value as like as two peas for the requested parameters must be exactly the same as those configured.

For example:

params = {"accountName"}, indicating that the request parameter must have accountName

​ params = {“moeny!100 "}, indicating that money in the request parameter cannot be 100

1.mvc namespace introduction

Namespace: 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

Component scan

Spring MVC is based on the spring container, so during spring MVC operation, 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" / > to scan the components.

3.4 XML configuration parsing of spring MVC

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

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

By browsing the source code of the parser, you can see the default settings of the parser, as follows:

REDIRECT_URL_PREFIX = "redirect:"  --Redirect prefix
FORWARD_URL_PREFIX = "forward:"    --Forwarding prefix (default)
prefix = "";     --View name prefix
suffix = "";     --View name suffix
  1. view resolver

We can modify the pre suffix of the view by attribute injection

<!--Configure internal resource view parser-->
<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 spring MVC

Front end controller: dispatcher Servlet

Processor mapper: HandlerMapping

Processor adapter: HandlerAdapter

Processor: Handler

View Resolver: View Resolver

Views: View

Annotation and configuration of spring MVC

Request mapping annotation: @ RequestMapping

View parser configuration:

REDIRECT_URL_PREFIX = "redirect:"

FORWARD_URL_PREFIX = "forward:"

prefix = "";

suffix = "";

ue=".jsp">

### 3.5 key points of knowledge

**SpringMVC Related components of** 

Front end controller: DispatcherServlet

Processor mapper: HandlerMapping

Processor adapter: HandlerAdapter

Processor: Handler

View parser: View Resolver

View: View

**SpringMVC Annotation and configuration of** 

Request mapping annotation:@RequestMapping

View parser configuration:

REDIRECT_URL_PREFIX = "redirect:"  

FORWARD_URL_PREFIX = "forward:"    

prefix = "";     

suffix = "";     

Tags: Java Spring mvc

Posted on Sat, 04 Sep 2021 01:20:27 -0400 by evildarren