For SpringMVC summary
1. Spring simplifies the acquisition of IOC containers
1.1 the principle
- In Spring learning, we usually get IOC containers
new ClasspathXmlApplicationContext(applicationContest.xml)
The downside of this approach is that every time you fetch a Bean from IOC, you need to new it and load the applicationcontest.xml file multiple times. - In a Web project, we can use listeners to listen for the start of the Web application. When the Web application starts, the Spring configuration file applicationContext.xml is automatically loaded, the container is created, and the container is stored in the maximum scoped servletContext in the Servlet. The IOC container stored in the servletContext can then be retrieved anywhere. To get the Bean.
- Spring simplifies this process for us by simply calling the corresponding API.
- Spring provides a ContextLoaderListener that loads the configuration file internally, creates the IOC container, and stores it in the ServletContext domain. And provide a client tool WebApplicationContextUtils for users to get the container.
1.2 How to use Spring’s listener to obtain IOC
- Import Spring-Web coordinates (POM.xml)
- Configure the ContextLoaderListener in web. XML.
- Use WebApplicationContextUtils to obtain the IOC container.
Example:
- Import coordinates for Spring integration Web
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5. RELEASE</version>
</dependency>
Copy the code
- Configure the ContextLoaderListener in web. XML
<! -- Spring configuration file specified as applicationContext.xml in classpath -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<! --Spring listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Copy the code
- Through WebApplicationContextUtils tools to obtain the IOC container.
ApplicationContext applicationContext =
WebApplicationContextUtils.getWebApplicationContext(servletContext);
Object obj = applicationContext.getBean("id");
Copy the code
2. Overview of SpringMVC
- SpringMVC is currently the mainstream enterprise-level development framework to implement THE MVC design pattern. It is a sub-module of spring framework, which requires no integration and is more convenient to develop.
- MVC design pattern: the application program is divided into Controller,Model and View. Controller receives client requests and calls Model to generate business data, which is passed to View.
- SpringMVC is the encapsulation of this process, shielding a lot of low-level code and opening the outbound interface, so that developers can more easily and conveniently complete web development based on MVC pattern.
3. Creation of springMVC container and its relationship with Spring container
Web.xml (only for spring and SpringMVC configuration, others omitted)
<! -- Spring configuration file specified as applicationContext.xml in classpath -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<! -- Spring listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<! Spring MVC core: Distributing servlets
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<! -- The configuration file of springMVC is springMVC. XML in classpath -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<! -- indicates that the container loads the servlet immediately upon startup -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<! -- Handle all urls, i.e. all requests go through DispatcherServlet-->
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Copy the code
- When Tomcat is started, the Listener,Filter, and Servlet in the web. XML configuration are loaded in sequence. When the Listener is loaded, the Spring IOC container is created according to the ContextLoaderListener Listener. The springMVC container is created in the DispatcherServlet based on the spring IOC container created above. The Spring container is the parent and springMVC is the child.
- Beans in Spring refer to Java objects that are instantiated, assembled, and managed by the Spring container.
- Both Spring and Spring MVC are containers for managing bean objects. SpringMVC is the container for managing Controller objects (beans), and Spring is the container for managing Service and Dao objects. Therefore, the scan path configured in the springMVC configuration file is the path of controller, while the spring configuration file is configured with the path of Service and DAO
- The Spring container and the springMVC container are parent containers. The Spring container is the parent and springMVC is the child. Objects (beans) in the child container can be accessed, but objects (beans) in the child container cannot be accessed. You can access the Service DAO object in the controller, but you cannot access the Controller object in the service DAO.
- Note: It is also possible to leave the ContextLoaderListener unconfigured in web.xml so that all beans are placed in the springMVC container created by the DispatcherServlet.
4. For SpringMVC primer
- A quick example: the client initiates the request, the server receives the request, executes the logic, and jumps to the view.
4.1 Development Procedure
- Import the coordinates of SpringMVC
- Configure the SpringMVC core controller DispathcerServlet
- Create the Controller class and view page
- Use annotations to configure the mapping address of the business method in the Controller class
- Configure the SpringMVC core file spring-mVC.xml
- The client initiates a request test
4.2 Code Implementation
-
Import the coordinates of Spring and SpringMVC in POM.xml, and import the coordinates of Servlet and JSP
<! - Spring coordinates -- -- > <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5. RELEASE</version> </dependency> <! - for SpringMVC coordinates - > <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.5. RELEASE</version> </dependency> <! - the Servlet coordinates - > <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <! - the Jsp coordinates - > <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> Copy the code
-
Configure the SpringMVC core controller in web.xml
// Create the springMVC container with DispatcherServlet and load the spring-mvc.xml configuration file<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> <! -- Handle all urls, i.e. all requests go through DispatcherServlet--> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> Copy the code
-
Create a Controller class
public class QuickController { public String quickMethod(a){ System.out.println("quickMethod running....."); return "index"; }}Copy the code
View interface (/ web-INF/JSP /index.jsp)
<html> <body> <h2>Hello SpringMVC!</h2> </body> </html> Copy the code
-
Use annotations to configure the mapping address of the business method in the Controller class
@Controller// Add the QuickController class object to the SpringMVC container @RequestMapping("")// Use to establish a mapping between the request URL and the method used to process the request public class QuickController { @RequestMapping("/quick") public String quickMethod(a){ System.out.println("quickMethod running....."); return "index"; }}Copy the code
-
Configure the SpringMVC core file spring-mVC.xml
<! -- Configure annotation scanning to scan annotations under Controller --> <context:component-scan base-package="com.itheima"/> <! -- Configure the view parser to parse the string returned from the Controller class by adding/web-INF/JSP/and.jsp --> <! This will enable DispatchServlet to find the location of index.jsp instead of a string representing the name of the file. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> Copy the code
-
The client initiates a request test
http://localhost:8080/itheima_springmvc1/quick Copy the code
Page display:
4.3 Process Analysis
- When the browser visits the test address, Tomcat receives the customer’s request and passes it to the front-end Controller (DispatchServlet), which finds the corresponding Controller processor class based on the URL. (Quick = requestMapping(“/quick”)) then execute the Controller class QuickController and print quickMethod Running….. on the console That string is returned to the DispatchServlet front controller, which doesn’t know what “index” means and passes it to the view parser (as configured in spring-mVC.xml). The result is parsed by the view parser and returned, and the front-end controller outputs the resulting index.jsp page to the browser. As you can see, the most important of these is the front-end controller DispatchServlet
- The above is a simple analysis of the SpringMVC process, which is actually a bit more complicated than this, and we will go into the details below. At the same time, as long as we understand the process, there is very little we need to write code in the actual development, the SpringMVC framework automatically does it for us, but this process should be understood!
5. Implementation process and analysis of SpringMVC
5.1 Execution Process
5.2 SpringMVC core components
- DispatcherServlet: Front-end controller, as the core of the whole SpringMVC process control, controls the execution of other components, carries out unified scheduling, reduces the coupling between components, and is equivalent to the commander in chief.
- HandlerMapping: A processor mapper that maps a client request to the Controller class and finds the specific handler (the Controller class) based on the request, usually using annotations, such as requestMapping(“/ XXX “).
- HandlerExecutionChain: The processor execution chain consists of two parts: Handler and HandlerInterceptor. (The processor interceptor is an interface that can be implemented if some intercepting is required. The system has a default interface that is implemented only when additional interceptions are required.)
- HandlerAdaptor: The Handler needs to perform a series of operations before performing business operations, including form data validation, data type conversion, form data encapsulation into javaBean, etc. These operations are completed by HandlerAdaptor. Developers only need to focus on the processing of business logic. The DispatcherServlet executes different handlers through the HandlerAdaptor.
- Handler: The Handler, the Controller class, is the business controller we will write in detail in our development. The DispatcherServlet forwards user requests to the Handler. Handler Processes specific user requests. After processing, return to ModelAndView
- ViewResolver: the View parser is responsible for parsing the passed ModelAndView and generating View View. The ViewResolver first parses the logical View into the physical View name, that is, the specific page address, and generates View View objects, which are returned to the front-end controller.
- View View: It is used to render the data model and present the data in the model to the client as a MIME type. Common MIME types are tetx/ HTML,image/ JPEG, etc.
The MIME type: www.w3school.com.cn/media/media…
5.3 Text description of the Execution process
- The user sends the request to the DispatcherServlet of the front-end controller
- The front-end controller invokes the HandlerMapping processor mapper on request
- The processor mapper finds the specific processor Handler and generates the processor object and the processor interceptor, which it returns to the front-end controller as a processor execution chain.
- The front-end controller first accesses the HandlerAdapter processor adapter based on the processor in the processor execution chain,
- The adapter is adapted to call a specific handler (controller).
- The Controller returns to ModelAndView after executing the logic.
- The HandlerAdapter passes the ModelAndView to the front controller.
- The front controller passes the ModelAndView to the ViewReslover view parser for parsing
- ViewReslover The View parser returns the specific View to the front-end controller
- The front controller renders the view (populates the view with model data) based on the returned view.
- The front-end controller returns the results to the client browser.
6. Relevant annotations for SpringMVC
@RequestMapping
- SpringMVC uses the @RequestMapping annotation to map THE URL request to the business method Controller. The @RequestMapping annotation can be added to the class definition of the Handler as well as to the method.
- Related parameters:
- value: Specifies the actual URL request address. This is the default value of @requestMapping. For example,
@RequestMapping("/index")
Is equivalent to@@RequestMapping(value="/index")
, so value can be omitted. - method: Specifies the request method type, GET,POST,PUT,DELETE, and so on. For example,
@RequestMapping(value="/index",method=ReauestMethod.GET)
The method that represents this annotation modifier can only accept the URL of the GET request. Browser requests are mostly GET, form requests are POST, and other requests can be demonstrated via Postman. - Params: Specifies that certain parameters must be included in the request or the method cannot be called.
@RequestMapping(value="/index",method=ReauestMethod.GET,params={"name","id=10"})
Indicates that the request must contain the name and ID parameters, and the id value must be 10
- value: Specifies the actual URL request address. This is the default value of @requestMapping. For example,
@Controller
- @Controller is added at the class definition to indicate that the class is managed by the springMVC container (by enabling automatic scanning of the Controller package in the springMVC.xml configuration file), and that it becomes a Controller that can receive client requests.
@RestController
- The @RestController annotation is a combination of @Controller and @responseBody, indicating that this is a Controller Bean and returning the value directly to the BODY of the HTTP response. It’s also a collection of @controller and @responseBody annotations.
- The object data returned by @RestController is written directly to the HTTP response body as JSON or XML.
@RequestParam
- This annotation is needed for manual mapping when the request parameter name is inconsistent with the Controller method parameter name, that is, cannot be mapped automatically.
When the request parameter is name and the received parameter is username, this annotation is needed for mapping. This is done by the HandlerAdapter processor mapper.
public void save16(@RequestParam(value="name") String username)
There are also a few parameters to choose from:
@RequestParam(value="name",required=false,defaultValue="hello")
Value: Assigns the value of the request parameter to the parameter it decorates, corresponding to the name of the request parameter
Required: The default is true if no write is required, indicating that the request parameters in the request cannot be empty. It can be set to false to indicate that the request parameter is null.
DefaultValue: you can give the request parameter a defaultValue of hello when required is false, that is, when the request parameter is null.
@Autowired*
@PathVariable
url:http://localhost:8080/quick17/zhangsan
@RequestMapping("/quick17/{name}")
@ResponseBody
public void save17(@PathVariable(value="name") String username) throws IOException {
System.out.println(username);
}
Copy the code
- The @pathVariable annotation is used to map the placeholder {name} in @requestMapping (“/quick17/{name}”) to the parameter username. Commonly used in restful urls.
- Note: @requestMapping (“/quick17/{name}”) matches @pathVariable (value=”name”). You can change the form of username
- See 10.10 to obtain Restful parameters
@PathParam*
@ResponseBody
- This annotation is used on methods in the Controller class to tell the SpringMVC framework that the method does not jump to the view and responds directly to the data. The ResponseBody method returns a string that is returned directly in the BODY of the HTTP response, rather than jumping to the page.
@RequestBody
- In the parameter list, it is used to encapsulate the fixed format data (JSON or XML) sent from the foreground into the corresponding javaBean object (one object used in encapsulation is the default configuration of SpringMVC HttpMessageConverter for parsing, and then encapsulated in the parameter).
- The @requestBody annotation is often used to handle content-type application/json (i.e. content-type is not the default Application/X-www-form-urlcoded), for example: Application/JSON or Application/XML etc.). If @requestBody is also used, the request mode is post, and the get mode returns NULL
@RequestHeader
-
You can get the request header information for the HTTP request message.
-
The @requestheader annotation has the following attributes:
Value: specifies the name of the request header
Required: Whether this request header must be carried
-
For details, see 10.12 Getting A Message in a Request Header.
@CookieValue
-
Gets the value of the Cookie in the request header
-
The @cookievalue annotation has the following attributes:
Value: Specifies the name of the cookie
Required: Whether this cookie must be carried
-
For details, see 10.12 Getting A Message in a Request Header.
@PostMapping
@PostMapping("users")
Is equivalent to@RequestMapping(value="/users",method=RequestMethod.POST)
@GetMapping
@GetMapping("users")
Is equivalent to@RequestMapping(value="/users",method=RequestMethod.GET)
7. Analysis of spring-mVC.xml configuration file
7.1 Annotation Scanning
<context:component-scan base-package="Com. Itheima. Controller"/ >
Copy the code
Represents loading all classes labeled @Controller under the Controller package into the springMVC container.
7.2 View Resolver
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
Copy the code
Represents parsing the ModelAndView returned by handler. For example, if the string “index” is returned, it is preceded by/web-INF /views/ and followed by.jsp.
7.3 Annotation Driver
<mvc:annotation-driven/>
Copy the code
In for springmvc. XML configuration, loading RequestMappingHandlerMapping automatically (processor mapper) and RequestMappingHandlerAdapter (processor adapter). The default processor mapper and processor adapter will be loaded without configuration.
Another benefit is that after configuration, Jackson is integrated at the bottom for converting jSON-formatted strings of objects or collections.
7.4 Enabling Static Resource Access
<! Enable static resource access -->
<mvc:default-servlet-handler />
Copy the code
This tag means that when the requested URL passes through the front-end Controller to HandlerMapping, if the Controller’s corresponding RequestMapping cannot be found, the default Tomcat server will be used to find the default resource.
7.5 Uploading Files
<! -- Config file upload resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">// Set the encoding and upload file size<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="500000"/>
</bean>
Copy the code
For details, see 11.2 Uploading a Single File
7.6 the interceptor
<mvc:interceptors>
<mvc:interceptor>
<! -- Which resources are intercepted -->
<! --/admin/** intercepts all files under /admin/
<! --/** Includes the path and its subpaths, i.e. intercepts all resources -->
<mvc:mapping path="/ * *"/>
<! The interceptor is configured for the bean.
<bean id="loginInterceptor" class="com.southwind.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
Copy the code
See 12. Springmvc interceptor
8. Analysis of web.xml configuration files (Supplement)
8.1 Chinese Filter
<! -- Chinese filter -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code
8.2 Spring configuration files and listeners
<! -- Spring configuration file specified as applicationContext.xml in classpath -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<! -- Spring listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Copy the code
- The main function is to help us create an IOC container by automatically loading configuration files through spring configuration listeners.
- See 1.2 How to Use Spring listeners to obtain IOC
8.3 SpringMVC Configuration File
<! Spring MVC core: Distributing servlets
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<! -- The configuration file of springMVC is springMVC. XML in classpath -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<! -- indicates that the container loads the servlet immediately upon startup -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<! -- Handle all urls, i.e. all requests go through DispatcherServlet-->
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Copy the code
- The main function is to create a springMVC container in the DispatcherServlet according to the spring-mVC.xml configuration file and then complete initialization.
- Access to static resources can be enabled in springMVC.xml so that when accessing static resources, the front-end controller releases the corresponding URL.
9. SpringMVC data response
9.1 springMVC Mandatory String Difference between springMVC and ModelAndView
- These two approaches come from different versions of Spring. The ModelAndView method was the primary method of returning models and views from controllers prior to Spring2.0. You can now combine Model parameters with String returns, but the old method still works. In principle they are the same, depending on the custom, you can choose either one.
9.2 The Value is returned as String- Page redirect
- Forwarding: Forwarding is a request with the same address bar path. You can share data with the Request object. Only resources under the current server can be accessed.
- Redirection: The address bar path has changed. There are two requests. The request object cannot be used to share data. You can access resources from other servers.
9.3 Return through ModelAndView object – Page hopping
Form 1: The Controller method returns the ModelAndView object and sets the view name:
@RequestMapping("/quick1")
public ModelAndView save1(a){
//Model: encapsulates data
//View: displays data
// Create a ModelAndView object
ModelAndView modelAndView = new ModelAndView();
// Set the model data
modelAndView.addobject("username"."itcast");
// Set the view name
modelAndView.setViewName("success");
return modelAndView;
}
Copy the code
The returned modelAndView is parsed by the view parser, converting the logical view SUCCESS in setViewName(” SUCCESS “) to the physical view xx/xx/success.jsp, where values in the model data can be retrieved using the EL tag. ${“username”}=itcast
Add: EL expression:
The purpose of EL expressions is to replace and simplify Java code writing in JSP pages. JSP supports el expressions by default. <% @page isELIgnored=”false” %> is set to true in JSP page directives
Form 2: Declare ModelAndView directly on the method parameter in the Controller. You do not need to create the view in the method. You can also jump to the page by using this object directly in the method.
@RequestMapping("/qiuck2")
public ModelAndView save2(ModelAndView modelAndView){
modelAndView.addObject("username"."itheima");
modelAndView.setViewName("success");
return modelAndView;
}
Copy the code
When SpringMVC calls the corresponding method, it automatically creates the corresponding object based on the type of the object parameter in the method and then invokes the method. This process is automated by SpringMVC.
Form 3: Use a combination of Model and string
@RequestMapping("/qiuck3")
public String save3(Model model){
model.addAttribute("username"."itheima");
return "success";
}
Copy the code
Note: The difference between Model and ModelAndView is that Model is only used to transmit data. ModelAndView can transmit data and do business addressing, that is, return to the specified static file (JSP).
Also in success.jsp, you can obtain the value itheima with the EL tag ${“username”}.
Form 4: You can use the native HttpServletRequest object directly on the parameters of the Controller method, just by declaring it.
@RequestMapping("/qiuck4")
public String save4(HttpServletRequest request){
request.setAttribute("username"."hello");
return "success";
}
Copy the code
Same as above.
9.4 Return string – Write back data
Form 1: returns a string that needs to be written back directly to the client browser. Add an @responsebody annotation to tell the SpringMVC framework that the string returned by the method does not jump to the page but is returned directly in the HTTP ResponseBody, i.e. displayed directly on the browser page.
@RequestMapping(value="/quick5")
@ResponseBody // Tell the SpringMVC framework not to jump to the view and respond directly to the data
public String save5(a) throws IOException{
return "hello itheima";
}
Copy the code
You will see the Hello itheima string in your browser
Form 2: The Response object injected by SpringMVC framework uses response.getwriter ().print() to write back data.
@RequestMapping("/quick6")
pubilc void save6(HttpServletResponse response) throws IOException{
response.getWriter().print("hello itheima");
}
Copy the code
You’ll also see Hello itheima in your browser
9.5 Returns an object or collection or a JSON-formatted string – writes back data
Json’s quick start: mp.weixin.qq.com/s/RAqRKZJqs…
Format 1: Write back a STRING in JSON format
@RequestMapping("/quick7")
@ResponseBody
public String save7(a) throws IOException{
return "{\"username\":\"zhangsan\",\"age\":18}"
}
Copy the code
Form 2: Use a JSON conversion tool to return a STRING in JSON format
Manual concatenation of JSON-formatted strings is troublesome. In development, complex Java objects are often converted into JSON-formatted strings. We can use the JSON conversion tool Jackson to convert JSON-formatted strings and write back data.
@RequestMapping("/quick8")
@ResponseBody
public String save8(a) throws IOEXception{
User user=new User();
user.setUsername("lisi");
user.setAge(30);
// Use the JSON conversion tool to convert the object to a JSON-formatted string and return it
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(user);
return json;
}
Copy the code
Note: Using the JSON conversion tool, import the coordinates of the three packages in POP.xml: Jsonson-core, Jackson-Databind, and Jackson-Annotations
Form 3: Returns a JSON string through the SpringMVC configuration
Configuration in springMVC.xml
// Configure the processor mapper. Springmvc implements the processor mapper internally, but manually reconfigure the processor mapper to convert json<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
Copy the code
Java code:
@RequestMapping("/quick9")
@ResponseBody
// Expect SpringMVC to automatically convert the User to a JSON-formatted string
public User save10(a) throws IOException {
User user = new User();
user.setUsername("lisi2");
user.setAge(32);
return user;
}
Copy the code
By configuring code in SpringMVC.xml, springMVC helps us automatically convert objects to JSON strings without needing to do anything else.
Form 4: Returns a JSON string through SpringMVC simplified configuration
Configure the annotation driver in springMVC.xml
<mvc:annotation-driven/>
Copy the code
Java code
@RequestMapping("/quick10")
@ResponseBody
// Expect SpringMVC to automatically convert the User to a JSON-formatted string
public User save10(a) throws IOException {
User user = new User();
user.setUsername("lisi2");
user.setAge(32);
return user;
}
Copy the code
The configuration in form 3 is cumbersome and can be simplified to form 4. Using < MVC :annotation-driven/>, the underlying layer inherits Jackson for converting jSON-formatted strings of objects or collections.
conclusion
All four forms have the same function, but gradually optimized, using form four is the most convenient, and most commonly used
10. Request acquisition of SpringMVC
10.1 Types of Request Parameters
-
The format of the client request parameters is: name= Value&Name =value… .
-
Type:
Basic data type parameters
Pojo type parameter
Array type parameter
Set type parameter
10.2 Obtaining Parameters of basic types
- The parameter name of the business method in the Controller should be the same as the name of the request parameter, the parameter value will be automatically mapped and matched, and the type conversion can be performed automatically.
- Automatic casting refers to converting from String to another type. For example, String to int
Get request url: http://localhost:8080/quick10? username=zhangsan&age=12
@RequestMapping("/quick11")
@ResponseBody
public void save11(String username,int age) throws IOException{
System.out.println(username);
System.out.println(age);
}
Copy the code
Note: The type name in the request URL must be the same as the parameter name in the method. So SpringMVC framework will automatically map for us, username=zhangsan will automatically assign parameter username,age=12 12 will automatically assign parameter age, and convert to the type of the parameter defined in the method.
10.3 Obtaining poJO /javaBean type parameters
-
The attribute name of the poJO parameter of the business method in the Controller is the same as the name of the request parameter, and the parameter values are automatically mapped and matched.
Pojo classes (POJOs: simple Java objects, javabeans)
import lombok.Data; @Data/ / generates getters, setters, toString public class User{ private String username; private int age; } Copy the code
Controller:
@RequestMapping("/quick12") @ResponseBody public void save12(User user) throws IOException{ System.out.println(user); } Copy the code
The requested url: http://localhost:8080/quick12? username=zhangsan&age=12
Because username and age in the request parameters correspond to the attribute names of user in the Controller method parameters, parameter mapping is automatically performed, assigning the values of username and age passed in to the username and age attributes of user. This process is done automatically by SpringMVC.
10.4 Getting the Parameters of the array type
- The name of the array of business methods in the Controller is the same as the name of the request parameter, and the parameter values are automatically mapped to match.
The requested url: http://localhost:8080/quick13? strs=111&strs=222&strs=333
@RequestMapping("/quick13")
@ResponseBody
public void quick13(String[] strs) throws IOException{
System.out.println(Arrays.toString(strs));
}
Copy the code
SpringMVC automatically wraps the request parameters into an array when the passed array names correspond to parameters. Then call the arrays.tostring () method to output
10.5 Obtaining the parameters of the set type
-
To obtain the parameters of a collection type, wrap the collection parameters in a POJO.
Start by defining a submission form form.jsp:
<from action="${pageContext.request.contextPath}/quick14" method="post"><%-- indicates the first User object username,age --%><input type="text" name="userList[0].username"><br/> <input type="text" name="userList[0].age"><br/> <input type="text" name="userList[1].username"><br/> <input type="text" name="userList[1].age"><br/> <input type="submit" value="Submit"><br/> </from> Copy the code
UserList [0]. Username represents the username property of the first user object in the set userList.
Define a user class with username and age attributes.
Define a class VO
import lombok.Data; @Data/ / generates getters, setters, toString public class VO { private List<User> userList; } Copy the code
The Controller class
@RequestMapping("/quick14") @ResponseBody public void save14(VO vo) throws IOException { System.out.println(vo); } Copy the code
The requested url: http://localhost:8080/form.jsp
After entering the form information, it jumps to the Controller method, passes the userList set data to VO, and prints:
VO{userList=[User{username=’zhangsan’,age=18},User{username=’lisi’,age=20}]}
10.6 Get parameter 2 of the collection type
- When submitting using Ajax, you can specify the contentType as JSON, so using @RequestBody in the method argument location can receive the collection data directly without wrapping it with a POJO.
Define the Ajax code ajax.jsp
<html>
<head>
<script src="${pageContext. Request. ContextPath} / js/jquery - 3.3.1. Js." "></script>
<script>
var userList = new Array(a); userList.push({username:"zhangsan".age:18});
userList.push({username:"lisi".age:28});
$.ajax({
type:"POST".url:"${pageContext.request.contextPath}/user/quick15".data:JSON.stringify(userList),
contentType:"application/json; charset=utf-8"
});
</script>
</head>
<body></body>
</html>
Copy the code
Controller:
@RequestMapping("/quick15")
@ResponseBody
public void save15(@RequestBody List<User> userList) throws IOException {
System.out.println(userList);
}
Copy the code
Analysis: the request Url: http://localhost/ajax.jsp, this Url will submit three requests to the server, the first visit ajax, JSP, second visit/js/jquery – 3.3.1. Js, quick15 third visit to jump. When accessing Quick15, the @RequestBody annotation converts the incoming JSON-formatted data into a javaBean, which the userList retrieves and outputs.
[User{username=’zhangsan’,age=18}, User{username=’lisi’,age=28}]
RequestBody @requestBody In the parameter list, it is used to encapsulate the fixed format data (JSON or XML) sent from the foreground into the corresponding javaBean object User. One object used in encapsulation is the default configuration of SpringMVC HttpMessageConverter for parsing. Then encapsulate it in the parameter userList, and print the userList to get the JSON to javaBean string.
The @requestBody annotation is often used to handle content-Type content that is not the default Application/X-www-form-urlcoded, such as Application/JSON or Application/XML. It is typically used to handle application/ JSON types. Select POST when using @requestBody and return NULL when using GET
10.7 The question above
-
When we visited the Ajax.jsp page, we found that the jQuery file was not loaded using Google’s package capture tool. The reason is that the URL-pattern of SpringMVC’s front-end controller DispatcherServlet is configured with /, so all URL requests will pass through the front-end controller DispatcherServlet and then be processed by HandlerMapping. But access to JSP pages is not suited to HandlerMapping, which handles user requests to a Controller, so we should not let DispatcherServlet manage request urls to access static resources, instead let static resources go
-
How to release static resources: Configure the location of static resources to be released in spring-mVC.xml
<mvc:resource mapping="/js/**" location="/js/"/> Copy the code
Or use the following tags:
<mvc:default-servlet-handler/> Copy the code
This tag means that when the requested URL passes through the front-end Controller to HandlerMapping, if the Controller’s corresponding RequestMapping cannot be found, the default Tomcat server will be used to find the default resource.
10.8 Configuring a Global Garble Filter
- When we make a request, if the parameter has Chinese characters, there may be data garbled. We can set a filter in the web.xml configuration file to filter the encoding.
<! -- Chinese filter -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code
10.9 The obtained parameters do not match the parameters
The parameter binding annotation @requestParam
- So we used to get primitive types, POJO types, array types of parameters by asking for a one-to-one mapping between the parameters and the Controller parameter method, and then SpringMVC did the mapping for us.
- If the request parameter name is inconsistent with the Controller’s business method parameter name, the @requestParam annotation is used to bind the parameters to complete the mapping between the HTTP request parameters and the Controller method parameters.
<form action="${pageContext.request.contextPath}/quick16" method="post">
<input type="text" name="name"><br>
<input type="submit" value="Submit"><br>
</form>
Copy the code
@RequestMapping(value="/quick16")
@ResponseBody
public void save16(@RequestParam(value="name") String username) throws IOException {
System.out.println(username);
}
Copy the code
-
The above code maps the request parameter name to the parameter username of the Controller method, with data type conversions if necessary. This is all done by the HandlerAdapter.
-
In addition, the @requestParam annotation has a few other parameters you can use. @RequestParam(value=”name”,required=false,defaultValue=”hello”)
Value: Assigns the value of the request parameter to the parameter it decorates, corresponding to the name of the request parameter
Required: The default is true if no write is required, indicating that the request parameters in the request cannot be empty. It can be set to false to indicate that the request parameter is null.
DefaultValue: you can give the request parameter a defaultValue of hello when required is false, that is, when the request parameter is null.
10.10 Get Restful parameters
-
What Restful is: Restful is a software architecture style, a design style, not a standard, that provides a set of design principles and constraints. Mainly used for client and server interaction software, based on this style, the design of software can be more concise, more hierarchical, easier to implement caching mechanisms, etc.
-
A Restful request uses “URL + request mode” to indicate the purpose of a request. The HTTP protocol has four verbs that indicate operation methods.
GET: Used to obtain resources
POST: Used to create resources
PUT: Updates resources
DELETE: Deletes resources
Such as:
/user/1 GET: GET the user whose ID is 1
/user/1 DELETE: deletes the user whose ID is 1
/user/1 PUT: Updates the user whose ID is 1
/user POST: Adds a user
-
Traditional versus Restful urls:
The traditional type: http://localhost:8080/user? name=zhangsan&id=10
Restful: http://localhost:8080/user/zhangsan/10
Note here that when accessing a URL in a browser, most operations are of the GET type.
-
/quick17/zhangsan can be written as /quick17/{name}, the placeholder {name} corresponds to zhangsan, Placeholders can be matched in business methods by using the @pathVariable annotation
url:http://localhost:8080/quick17/zhangsan
@RequestMapping("/quick17/{name}")
@ResponseBody
public void save17(@PathVariable(value="name") String username) throws IOException {
System.out.println(username);
}
Copy the code
- Value =”/quick17/{name} “; name = @pathVariable (value=”name”);
- Mapping request parameters to parameters is done using the @pathVariable annotation.
10.11 Customizing the Data Type Converter
- A data type converter converts parameters in a client HTTP request to parameters defined in a business method. SpringMVC provides some common type conversions by default, such as String to int,String to double, and form data encapsulation. This is done by the HandlerAdapter processor adapter.
- If we need a HandlerAdapter that cannot be converted, then we need to define a data type converter to do this.
Define a type converter to convert “2021-4-16” String data to Date.
Steps:
-
Define a Converter class to implement the Converter interface
-
The converter is declared in the spring-mVC.xml configuration file and referenced in
-
Method tests in the Controller package
Implementation:
- Define the Converter class DateConverter to implement the Converter interface
public class DateConverter implements Converter<String.Date>{
public Date convert(String dateStr){
// Convert a string to a Date object
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date=null;
try{
date=format.prase(dateStr);
}catch(ParseException e){
e.printStackTrace();
}
returndate; }}Copy the code
- Declare the converter in the springMVC.xml configuration file, in
<annotation-driven>
Reference converter
// Declare the converter<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="xxx.xxx.DateConverter"></bean>// This is the full class name of the custom converter class DateConverter</list>
</property>
</bean>// Configure the annotation driver, adding the id of the above bean to the following conversion-service<mvc:annotation-driven conversion-service="conversionService">
Copy the code
- Method tests in the Controller package
@RequestMapping("/quick18")
@ResponseBody
public void save18(Date date) throws IOException{
System.out.println(date);
}
Copy the code
The requested url: http://localhost:8080/quick18&date=2021-04-16
10.12 Obtaining the Information in the Request Header
- After entering the URL in the browser address bar, the browser parses the URL and generates different HTTP request messages based on different request modes (such as GET and POST).
- A refresher on HTTP:
GET request message format:
Request line: GET/URL HTTP/1.1
Request header: Some information that the client browser tells the server. Examples include dates, languages supported by the client, data types, compression formats, etc. Format: Request header name: Request header value.
Request blank line: Tells the server that the request header has ended.
POST request message format:
Request line: POST/URL HTTP/1.1
Request header: Some information that the client browser tells the server
Request blank line: Tells the server that the request header has ended.
Request body: Encapsulates the request parameters of the POST request message.
The difference between the two:
**GET: ** Request parameters in the request line, after the URL. The requested URL is limited in length and not very secure.
**POST: ** Request parameters In the request body, the request URL length is not limited, relatively safe.
- Use @requestheader to get the request header, which is equivalent to request. GetHeader (name) in the Web phase.
@RequestMapping("/quick19")
@ResponseBody
public void save19(@RequestHeader(value="User-Agent",required=false) String user_agent) throws IOException{
System.out.println(user_agent);
}
Copy the code
@requestheader attributes:
Value: specifies the name of the request header
Required: Whether this request header must be carried
- You can also get the value of the Cookie using the @requestheader annotation, but there is an easier annotation to get the Cookie: @cookievalue
@RequestMapping("/quick20")
@ResponseBody
public void save20(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
System.out.println(jsessionId);
}
Copy the code
The @cookievalue annotation has the following attributes:
Value: Specifies the name of the cookie
Required: Whether this cookie must be carried
10.13 Obtaining apis related to Servlets
SpringMVC supports injection using raw ServletAPI objects as arguments to controller methods. Common objects are as follows:
HttpServletRequest
HttpServletResponse
HttpSession
@RequestMapping(value="/quick21")
@ResponseBody
public void save21(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
System.out.println(request);
System.out.println(response);
System.out.println(session);
}
Copy the code
11. Upload SpringMVC file
11.1 Three elements of a client form
- Form entry: type=”file”
- Form submission: Post
- The encType attribute of the form is a multi-part form: encType =”multipart/form-data”. If this property is not set, only the file name can be passed to the server.
- Such as:
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">The name of the<input type="text" name="username"><br/>file<input type="file" name="uploadFile"><br/>
<input type="submit" value="Submit">
</form>
Copy the code
-
Note: the bottom line of fileupload is to use the Apache fileupload component to complete the upload, and SpringMVC encapsulates this approach.
-
Request.getparameter () becomes invalid when the form form changes to a multi-part form
11.2 Uploading a Single File
Steps:
- Import fileupload and IO coordinates in POM. XML
- Configure the file upload parser in sping-mvC.xml
- Write the form
- Write a Handler
Implementation:
- The leading coordinates in POM.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
Copy the code
- Configure the file upload parser in sping-mvC.xml
<! -- Config file upload resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">// Set the encoding and upload file size<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="500000"/>
</bean>
Copy the code
- Write the form
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">The name of the<input type="text" name="username"><br/>file<input type="file" name="uploadFile"><br/>
<input type="submit" value="Submit">
</form>
Copy the code
- Write a Handler
@RequestMapping(value="/quick22")
@ResponseBody
public void save22(String username, MultipartFile uploadFile) throws IOException {
System.out.println(username);
// Get the name of the uploaded file
String originalFilename=uploadFile.getOriginalFilename();
// Upload the uploaded file to the upload file name of disk C
uploadFile.transferTo(new File("c:\\upload\\"+originalFilename));
}
Copy the code
- Note: The MultipartFile uploadFile parameter in Handler must have the same name as the name attribute in the form.
11.3 Uploading Multiple Files
- Multifile upload, simply change the page to multiple file upload items, and change the method parameter MultipartFile type to MultipartFile[].
Implementation:
- Coordinates in pom.xml
- Configure the file upload parser in springMVC.xml
- Write the form
<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">The name of the<input type="text" name="username"><br/>File 1<input type="file" name="uploadFile"><br/>File 2<input type="file" name="uploadFile"><br/>
<input type="submit" value="Submit">
</form>
Copy the code
- Write a Handler
@RequestMapping("/quick23")
@ResponseBody
public void save23(String username, MultipartFile[] uploadFile) throws IOException {
System.out.println(username);
for (MultipartFile multipartFile : uploadFile) {
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("C:\\upload\\"+originalFilename)); }}Copy the code
12. SpringMVC interceptor
12.1 What is the Interceptor for springMVC
- SpringMVC’s interceptor is similar to the Filter used in Servlet development for pre-processing and post-processing of the processor.
- Interceptors are joined in a chain in a certain order, which is called an InterceptorChain. When the intercepted methods and fields are accessed, interceptors are invoked in the order they were previously defined.
- Interceptors are concrete applications of AOP ideas.
12.2 Differences between Filters and interceptors
The difference between | Filter Filter | The interceptor |
---|---|---|
Using range | Is part of the Servlet specification and can be used by any Java Web project | It is the springMVC framework’s own, and can only be used by projects that use the SpringMVC framework. |
Intercept range | After /* is configured in url-pattern, all resources to be accessed can be blocked | Only accessed controller methods are blocked, not JSP, HTML, CSS,image, or JS |
- The resources in the WEB-INF directory cannot be directly accessed by the browser. You need to access the Controller method, which can access the resources in the Web-INF directory through the view parser
- This is different from the previous front-end controller configuration. In the front-end controller configuration, we configured in web. XML to intercept all client requests and send them to the front-end controller dispatcherServlet. It is handled by the Controller method, or tomcat’s default servlet if it is a static resource.
- According to the above picture, webApp includes CSS, IMG, and WEB-INF directories. With the exception of the wen-INF resources, all are accessible by entering a specific address in the browser. Web-inf must be accessed by the Controller after being parsed by the view parser.
12.3 Quick Start: Customize an interceptor to authenticate user login
Implementation idea:
- There is a login page, and you need to write a Controller access page.
- The landing page has an action to submit the form. It needs to be handled in the controller. Check whether the user name and password are correct. If correct, write user information to session. Return landing successful
- Intercept user requests to determine whether the user is logged in. If the user is logged in. If the user does not log in, the login page is displayed
code
- Write a login interface login.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> title </title> </head> <body> <h1> Login page </h1> <hr> <form action="/user/login"> User name: <input type="text" name="username"> <br> Password: <input type="password" name="pwd"> <br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Copy the code
- Write a successful login interface success.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"% > < HTML > < head > < title > title < / title > < / head > < body > < h1 > login successful interface < / h1 > < hr > ${user} < a href ="/user/logout"> Log off </a> </body> </ HTML >Copy the code
- Write the start page on the default index.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > $title $< / title > < / head > < body > < h1 > home page < / h1 > < hr > < a href ="user/jumpLogin"> login </a> <a href="user/jumpSuccess"> Success page </a> </body> </ HTML >Copy the code
- Write controllers to handle requests
package com.southwind.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
/** * Created with Intellij IDEA * Description: * user: CoderChen * Date: 2021-05-05 * Time: 12:24 */
@Controller
@RequestMapping("/user")
public class userController {
// The login page is displayed
@RequestMapping("/jumpLogin")
public String jumpLogin(a) {
return "login";
}
// Go to the success page
@RequestMapping("/jumpSuccess")
public String jumpSuccess(a) {
return "success";
}
// Log in to submit
@RequestMapping("/login")
public String login(HttpSession session, String username, String pwd) {
System.out.println("Receiving front end ===" + username);
session.setAttribute("user", username);
return "success";
}
// Log out
@RequestMapping("/logout")
public String logout(HttpSession session) {
/ / the session has expired
The scope of a session is the moment the user opens the site until the browser closes, regardless of how many resources are accessed on the site during that time
// All belong to the same session
session.invalidate();
return "login"; }}Copy the code
- Configure the view parser and annotation scan in SpringMVC.xml
** Note: ** So far we can access the login screen. (as shown in figure)
** Problems: ** You can enter the successful login interface from the home page even if the login is not successful. You can’t do this in real development. Therefore, it is necessary to set up the interceptor to intercept the behavior of successfully entering the login successful interface without logging in.
- Write user login interception requests
package com.southwind.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/** * Created with Intellij IDEA * Description: * user: CoderChen * Date: 2021-05-05 * Time: 19:59 */
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("uri: " + request.getRequestURI());
// If it is a login page, pass it
if (request.getRequestURI().contains("login")) {
return true;
}
// If the user is already logged in, the system permits the login
HttpSession session = request.getSession();
if (session.getAttribute("user") != null) {
return true;
}
// The user jumps to the login page without logging in
request.getRequestDispatcher("/login.jsp").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}Copy the code
- Configure the register interceptor in springMVC.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/ * *"/>
<bean id="loginInterceptor" class="com.southwind.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
Copy the code
As shown in figure:
- According to the configuration of interceptors in SpringMVC.xml, all requests are intercepted. Then judge whether to release according to the conditions.
12.4 Description of interceptor API and configuration:
Custom interceptor class description:
Description of methods in interceptors
The method name | instructions |
---|---|
preHandle() | Method is called before the request is processed, executing the next interceptor if it returns true or not if it returns false. |
postHandle() | Is called after the request-handling method has executed, if the preHandle() method returns true.It is called before the DispatcherServlet renders the view return, so we can operate on the ModelAndView object after the Controller handles it in this method. |
afterCompletion() | Executes at the end of the entire request, doing the cleanup, if preHandle() returns true |
- If there are more than one interceptor, configure the first one to be executed and the last one to be executed in XML.
- In the interceptor, methods are executed in the following order: preHandle() — > Target Resource — >postHandle() — >afterCompletion()
Interceptor configuration in springMVC. XML:
<mvc:interceptors>
<mvc:interceptor>
<! -- Which resources are intercepted -->
<! --/admin/** intercepts all files under /admin/
<! --/** Includes the path and its subpaths, i.e. intercepts all resources -->
<mvc:mapping path="/ * *"/>
<! The interceptor is configured for the bean.
<bean id="loginInterceptor" class="com.southwind.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
Copy the code
12.5 Execution process of interceptor:
- When the request is sent from the client, it is first processed by the front-end controller of dispatcherServlet, and then the request is sent to the handlerMapping processor mapper to find the specific handler. HandlerMapping During processing, the processor mapper generates a chain of processor execution based on the handler and interceptor and sends it back to the front-end controller. The front-end controller performs operations sequentially based on this chain and sends them to the processor adapter HandlerAdaptor for subsequent operations.
- The defining point of the interceptor in this process is the HandlerMapping processor mapper. Interceptors have three methods, of which the preHandle() method is called before the request is processed by the business processor. The SpringMVC Interceptor is called in a chain manner, so there can be multiple interceptors in an application or in a request. Each Interceptor call is executed in the order in which it is declared, and the first one is the Interceptor preHandle method, so some pre-initialization or a pre-processing of the current request can be done in this method. You can also make some judgments in this method to determine whether the request should proceed. The return value of this method is Boolean. When it returns false, the request is complete. The Interceptor and Controller will not be returned. When the return value is true, the next Interceptor’s preHandle method is called, and the requested Controller method is called when the last Interceptor is intercepted.
- PostHandle () : This method is executed after the current request is processed, that is, after the Controller method is called, but it is called before the DispatcherServlet views return render, So we can operate on the ModelAndView object after the Controller handles it in this method. The postHandle method is called in the opposite direction from the preHandle method, which means that the postHandle method declared by the Interceptor first will be executed later.
- AfterCompletion () : This method is also executed only when the return value of the corresponding Interceptor’s preHandle method is true. As the name implies, this method is executed after the entire request is complete, after the Corresponding view has been rendered by the DispatcherServlet. The main purpose of this method is for resource cleanup. The afterCompletion method is called in the opposite direction from perHandle, declaring the afterCompletion method of the Interceptor first and then executing it.
- SpringMVC framework -springMVC interceptor principle (five) _ April Fool’s Day blog -CSDN blog _Spring interceptor implementation principle
13. SpringMVC exception handling
14 supplement
14.1 Knowledge of EL expressions
- How2j. Cn/JSP/JSP/k – e…
14.2 SpringMVC’s Controller automatically encapsulates form parameters as objects
- Blog.csdn.net/weixin_4040…