— All brain maps are made by myself, do not abuse without permission –!! The overall focus on SpringMVC source code analysis, combined with handwritten implementation of the full “get it to fish”

A quick review of SpringMVC

Part 1 – Introduction

1.1 the MVC system

Our development architecture is generally based on two forms, one is C/S architecture, that is, client/server; The other is the B/S architecture, which is the browser server. In B/S architecture, the system standard has three layers, including presentation layer, business layer and persistence layer. The presentation layer (presentation layer + control layer) is also known as the Web layer. Usually, the client uses HTTP to request the Web layer. The Web needs to receive HTTP requests and complete HTTP responses. The business layer is also known as the Service layer. Responsible for business logic processing. The persistence layer (data layer + data access layer) is also known as dao layer. Database is the carrier of data persistence; The data access layer is the interface between the business layer and the persistence layer

The Web layer depends on the business layer, but the business layer does not depend on the Web layer. The business layer may rely on the persistence layer for business processing. Transaction consistency is required to persist data. (As we said, transactions should be controlled in the business layer)

1.2 MVC design pattern

SpringMVC, full name of Spring Web MVC, is a java-based request-driven type of lightweight Web framework that implements MVC design model. It is a follow-up product of Spring Framework.

Spring MVC, like Struts2, is a Web framework designed to solve presentation problems. Both are based on the MVC design pattern. The main responsibility of these presentation layer frameworks is to handle front-end HTTP requests

Spring MVC essence can be thought of as the encapsulation of servlets

Part 2 – Workflow

Below image source: Java high salary boot camp

2.1 Process Analysis

  1. User sends request–>Front end controllerDispatcherServlet
  2. DispatcherServlet receives the request–>Processing mapperHandlerMapping
  3. HandlerMapping Finds the controller by URL –Handler, generator processor chain –HandlerExecutionChain, processor interceptor –HandlerInterceptor –>Returns the DispatcherServlet
  4. The DispatcherServlet invokes the processor adapterHandlerAdapterTo call the specified Handler
  5. The processor adapter executes the Handler
  6. Processor adapter returnsModelAndView –> DispatcherServlet
  7. DispatcherServlet request–>View parserViewResolverAnalytical view–>Return true View of DispatcherServlet
  8. DispatcherServlet renders the view, i.ePopulate the model data (in the ModelAndView object) into the Request field
  9. DispatcherServlet returns response result –> user

P.S. ModelAndView is an underlying object of the SpringMVC framework, including Model and View

2.2 Nine Components of Spring MVC

-A- HandlerMapping
Used to find handlers, which can be classes or methods


For example: marked
@RequestMappingEach method is a Handler


Handler is responsible for handling the request. After the request arrives, HandlerMapping is used to find the Handler and Interceptor corresponding to the request.
-B- HandlerAdapter
Because handlers can be arbitrary in Spring MVC, as long as they can handle requests.


But when it comes to handing requests to servlets, the Servlet’s method structure is
doService(HttpServletRequest req,HttpServletResponse resp)In the form of


It is the responsibility of the HandlerAdapter to have the fixed Servlet processing method call the Handler for processing
-c – HandlerExceptionResolver(processor exception parser)
HandlerExceptionResolver Handles exceptions generated by the Handler.


What it does is set up the ModelAndView according to the exception, which is then rendered by the rendering method, which renders the ModelAndView as a page
-d ViewResolver
There is only one View that resolves a String View name and Locale to a View
resolveViewName()Methods.


The String View name returned by the Controller layer, viewName, will eventually be resolved to View here


The View is used to render the page, that is, it fills the template with the parameters and data returned by the program to generate an HTML file.



The ViewResolver does two things in this process:


1. Find the template for rendering;


2. Find the view type and fill in the parameters



By default, the Spring MVC will automatically configure an InternalResourceViewResolver for us, is only for the type of JSP view.
– E – RequestToViewNameTranslator (request view translation)
Get the ViewName from the request


A ViewResolver finds a View by its ViewName, but some handlers do not set the View or the ViewName after processing it


This component is then used to look up the ViewName from the request
-F- LocaleResolver(area processor)
The resolveViewName method of the ViewResolver component takes two parameters: the view name and the Locale


LocaleResolver is used to resolve Locale from the request. For example, Chinese Locale is zh-CN, which indicates a region.



This component is also the basis of the I18N
-G- ThemeResolver(theme processor)
Used to parse topics


A theme is a collection of styles, images, and the display effects they form


A set of themes in Spring MVC corresponds to a properties file, which holds all resources related to the current theme, such as images, CSS styles, and so on


-H- MultipartResolver
For upload requests


The request of the ordinary packaged into MultipartHttpServletRequest


The MultipartResolver does just that
Encapsulate a common request with file upload functionality
– i-FlashMapManager (Refresh Set Manager)
Parameter passing for redirection


For example, when processing a user order, to avoid repeated submissions, you can process a POST request and then redirect to a GET request, which can be used to display information such as order details

Part 3 – Parameter binding

HTTP protocol is “hypertext Transfer Protocol” ————” hypertext “! Text “! So arguments from the Web side are all in the form of characters

Parameter binding – Takes the parameter value and binds it to the parameter of the handler method

3.1 Servlet APIS are supported as method parameters by default

When needed
HttpServletRequest, HttpServletResponse, HttpSessionAnd other native servlet objects


Use the parameter declaration directly in the handler method
// http://localhost:8080/test/handler? id=1
public ModelAndView handler(HttpServletRequest request, HttpServerletResponse response, HttpSession session) {
	String id = request.getParameter("id");
	Date date = new Date();
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.addObject("id", id);
	modelAndView.addObject("date", date);
    modelAndView.setViewName("success");
	return modelAndView;
}
Copy the code

3.2 Binding Simple Type Parameters

Eight basic data types and their wrapper types



The wrapper data type is recommended because the underlying data type cannot be null














For Boolean parameters, the request parameter value is true or false. Or 1 or 0. If the parameter name and the pass parameter name do not match, the @requestParam annotation can be used for manual mapping

// http://localhost:8080/test/handler? ids=1&flag=0
@RequestMapping("/handler")
public ModelAndView handler(@RequestParam("ids") Integer id,Boolean flag) {
	ModelAndView modelAndView = new ModelAndView();
	System.out.println(id + flag);
    modelAndView.setViewName("success");
	return modelAndView;
}
Copy the code

3.3 Binding Pojo Type Parameters

// http://localhost:8080/test/handler? id=1&username='archie'
@RequestMapping("/handler")
public ModelAndView handler(User user) {
	ModelAndView modelAndView = new ModelAndView();
	System.out.println(user.getId() + user.getUserName);
	modelAndView.setViewName("success");
	return modelAndView;
}
Copy the code

3.4 Binding Pojo wrapper object parameters

class User {
	private Integer id;
	private String userName;
	/ /... Omit get/set methods
}

class UserVO {
	private mail;
	private phone;
	/* Nested User */
	private User user;
	/ /... Omit get/set methods
}
Copy the code

The parameter name is the same as the POJO attribute. If the data item cannot be located, the attribute name + “.” is used to further lock the data

// http://localhost:8080/test/handler? user.id=1&user.username='archie'
@RequestMapping("/handler")
public ModelAndView handler(UserVO userVO) {
	ModelAndView modelAndView = new ModelAndView();
    System.out.println(userVO.getUser.getId() + userVO.getUser().getUserName);
	modelAndView.setViewName("success");
	return modelAndView;
}
Copy the code

3.5 Binding Date Type Parameters (User-defined Type Converter Needs to Be Configured)

The front-end JSP

<fieldset>
	<p>SpringMVC receives date type arguments</p>
    <a href="/test/handler? birthday=2020-12-10">Click on the test</a>
</fieldset>
Copy the code

handler

@RequestMapping("/handler")
public ModelAndView handler(Date birthday) {
	ModelAndView modelAndView = new ModelAndView();
	System.out.println(birthday);
	modelAndView.setViewName("success");
	return modelAndView;
}
Copy the code

Custom type converter

public class DateConverter implements Converter<String.Date> {
	@Override
	public Date convert(String source) {
		// Complete the conversion from string to date
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	}
	try {
		Date trueDate = simpleDateFormat.parse(source);
		return trueDate;
	} catch(ParseException e) {
		e.printStackTrace();
	}
	return null;
}
Copy the code

Register custom type converters

<! Automatically register the most appropriate processor mapper/processor adapter
<mvc:annotation-driven conversion-service="conversionServiceBean"/>
<! Register a custom type converter
<bean id="conversionServiceBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<property name="converters">
		<set>
			<bean class="com.archie.test.converter.DateConverter"/>
		</set>
	</property>
</bean>
Copy the code

Part 4-restful Style

4.1 what is a RESTful

REST
Representational State Transfer


The web software architecture style is not a standard or a protocol, but a style for locating and manipulating resources



All things on the Internet are resources, requiring urls to have only names for resources, no verbs.
  • Traditional URL:http://localhost:8080/user/queryUserById.action?id=1

    Defines theactionThe argument directly locks the operand
  • REST style URL:http://localhost:8080/user/3

    Only the resource object to be operated on is lockedThe resource with ID 3

    As for theactionDistinguish according to different request mode
Request classification:


Get Obtain resources


Post Creating a resource


Put Updates resources


Delete Delete a resource


For example:

/account/1 HTTP GET: GET the account whose ID is 1

/account/1 HTTP DELETE: DELETE the account whose ID is 1

/account/1 HTTP PUT: Updates the account whose ID is 1

4.2 RESTful Implementation using @PathVariable

The front form
<! Select * from user where id = 5 -->
<a href="/test/handle/15">The REST get request</a>
<! -- Add user Archie -->
<form method="post" action="/test/handle">
	<input type="text" name="username" value="Archie" />
	<input type="submit" name="Submit a REST POST request" />
</form>
<! Select * from Mick where id = 5 and name = Mick
<form method="post" action="/test/handle/15/Mick">
	<input type="hidden" name="_method" value="put" />
	<input type="submit" name="Submit a REST PUT request" />
</form>
<! Select * from user where id = 5;
<form method="post" action="/test/handle/15">
	<input type="hidden" name="_method" value="delete" />
	<input type="submit" name="Submit a REST DELETE request" />
</form>
Copy the code
The background Handler
@RequestMapping(value = "/handle/{id}", method = {RequestMethod.GET})
public ModelAndView handleGet(@PathVariable("id") Integer id) {
	ModelAndView modelAndView=new ModelAndView();
	System.out.println(id);
	return modelAndView;
}

@RequestMapping(value = "/handle", method = {RequestMethod.POST})
public ModelAndView handlePost(String username) {
	ModelAndView modelAndView=new ModelAndView();
	testService.save(username);
	return modelAndView;
}

@RequestMapping(value = "/handle/{id}/{username}", method = {RequestMethod.PUT})
public ModelAndView handlePut(@PathVariable("id") Integer id, @PathVariable("username") String userName) {
	ModelAndView modelAndView=new ModelAndView();
	testService.update(id, userName);
	return modelAndView;
}

@RequestMapping(value = "/handle/{id}", method = {RequestMethod.DELETE})
public ModelAndView handleDelete(@PathVariable("id") Integer id) {
	ModelAndView modelAndView=new ModelAndView();
	testService.delete(id);
	return modelAndView;
}
Copy the code
Configure request mode filters in web.xml (to convert specific POST requests to PUT and DELETE requests)
<filter>
	<filter-name>hiddenHttpMethodFilter</filter-name>
	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
	<filter-name>encoding</filter-name>
	<url-pattern>/ *</url-pattern>
</filter-mapping>

<filter-mapping>
	<filter-name>hiddenHttpMethodFilter</filter-name>
	<url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code

Part 5 – Ajax JSON interaction

1. Front-end to back-end


The front-end Ajax sends jSON-formatted strings, and the back-end receives them directly as POJO parameters, using annotations
@RequstBody



2. Background to front end


Pojo objects are returned directly from the background, and json objects or strings are received directly from the front, using annotations
@ResponseBody

5.1 what is a JSON

Json is a language-independent format for data interaction, just a string. Just use special symbols {} for objects, [] for arrays, “” for properties or values, and: to indicate that the latter is the value of the former

5.2 @ ResponseBody annotation

After converting the object returned by the Controller’s methods to the specified format through the appropriate converter, it is written to the body of the Response object, which is usually used to return JSON data or XML data.

After using this annotation, instead of going through the view processor, the data is written directly to the input stream, which has the same effect as writing data in the specified format through the Response object

5.3 Analyzing SpringMVC using JSON interaction

The required JAR package is imported
<! -- jar for json data interaction, start-->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>2.9.0</version>
</dependency>
Copy the code
Front-end JSP and JS
<div>
	<h2>Ajax json interaction</h2>
	<fieldset>< inputtype = "button" id = "ajaxBtn" value = "ajax submit" / ></fieldset>
</div>
Copy the code
$(function () {$("#ajaxBtn").bind("click".function() {
		$.ajax({
			url: '/test/handle'.type: 'POST'.data: '{"id":"1","username":"Arice"}'.contentType: 'application/json; charset=utf-8'.dataType: 'json'.success: function (data) { alert(data.name); }})})})Copy the code
The background Handler
// After adding @responseBody, instead of going through the view parser process, output data equivalent to response
@RequestMapping(value = "/handle")
public @ResponseBody handle(@RequesetBody User user) {
	user.setName("Mick");
	return user;
}
Copy the code

SpringMVC advanced technology

Part 1 interceptor (Inteceptor) used

1.1 Comparison of listeners, filters and interceptors

  • Servlet: Handles Request requests and Response responses
  • Filter: filters Request requests before servlets. If the Filter is set to /*, all resource access (servlets, JS/CSS static resources, etc.) is filtered
  • Listener: Implements the javax.mail. Servlet. The ServletContextListener interface server-side components, it along with the start of the Web application starts, initialized only once, and then will have been running monitoring, along with the stop and destroy a Web application: Do some initialization, the spring container to start the ContextLoaderListener role in web application 2: listen to a specific event in the web, such as the HttpSession ServletRequest creation and destruction; Creation, destruction, and modification of variables.
  • Interceptor:

    Is the SpringMVC, Struts and other presentation layer frameworks themselves,Does not block access to JSP/HTML/CSS /image, etc., only access to controller methods (Handler)
  • Summary: Serlvet, filter, listener are configured in web.xml, while interceptor is configured in the presentation framework’s own configuration file

1.2 Interceptor execution process

1.3 Execution process of multiple interceptors

To follow up

Part 2 handles data in multipart form

The required jars
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>
Copy the code
Configuration file upload parser
<! -- Config file upload resolver, id fixed multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<! -- Set upload size in bytes -->
	<property name="maxUploadSize" value="1000000000" />
</bean>
Copy the code
The front form
<%--
	1 method="post"
	2 enctype="multipart/form-data"
	3 type="file"
--%>

<form method="post" action="/test/upload" enctype="multipart/form-data">
	<input type="file" name="uploadFile" />
	<input type="submit" name="Upload" />
</form>
Copy the code
The background Handler
@RequestMethod("upload")
public Stirng upload(MultipartFile uploadFile, HttpServletRequest request) throws IOException{
	// The original name of the file is xxx.jpg
	String originalFileName = uploadFile.getOriginalFileName();
	// Get the extension of the file
	String extendName = originalFileName.substring(originalFileName.lastIndexOf(".") + 1,
		originalFileName.length());
	String uuid = UUID.randomUUID().toString();
	// The new file name
	String newName = uuid + "." + extendName;
	String realPath = request.getSession().getServletContext().getRealPath("/uploads");
	// Resolve the limit on the number of files stored in folders -- > store by date
	String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
	File floder = new File(realPaht + "/" + datePath);
	if(! floder.exists()) { floder.mkdirs(); } uploadFile.transferTo(new File(floder, newName));
	return "success";
}
Copy the code

Part 3 Handling exceptions in controllers

@ControllerAdvice
public class GlobalExceptionResolver {

	@ExceptionHandler(ArithmeticException.class)
	public ModelAndView handleException(ArithmeticException exception, HttpServletRequest response) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("msg", exception.getMessage());
		modelAndView.setViewName("error");
		returnmodelAndView; }}Copy the code

Part 4 Cross-redirect request data transfer based on Flash attributes

The forwarding URL remains unchanged/the parameters are not lost/It is the same request that A borrows 100 yuan from B, but B does not, but B manages to collect 100 yuan to A. The redirection url will change/The parameters will be lost/It is not the same request that A borrows 100 yuan from B, but B does not, so HE directly asks A to borrow from others

When redirecting request parameters will be lost, we often need to re-carry the request parameters, we can do manual parameter splicing as follows

return"redirect:handle01? name="+name;

However, the above method of concatenating parameters belongs to GET request, and the length of parameters is limited


At this point, we can use what SpringMVC provides
Flash Attribute MechanismTo add flash attributes to the context


The framework records the value of the flash attribute in the session and automatically deletes the flash attribute when jumping to the page



Length and safety are guaranteed
@RequestMapping("/handleRedirect")
public String handleRedirect(String name,RedirectAttributes redirectAttributes) {
	// The addFlashAttribute method sets a flash attribute,
	// This property is stored temporarily in the session and destroyed after jumping to the page
	redirectAttributes.addFlashAttribute("name",name);
	return"redirect:handle01";
}
Copy the code

Handwriting SpringMVC framework

Part 1 Core functions

  1. The custom@ Controller annotationsAnd implement
  2. The custom@ Service annotationsAnd implement
  3. The customThe @autowired annotationAnd implement
  4. The custom@ RequestMapping annotationsAnd implement
  5. The custom@ Security annotationsAnd implement
  6. Construct important POJOs – Handler Stores information about handlers
  7. Custom DispatcherServlet and implementation
  8. Custom component handlerMapping and implementation

Part 2 Project structure

Part 3 Focus on key points


The overall code is as follows, you can directly run the implementation code

Four, SpringMVC source code analysis

To follow up

5. SSM integration

To follow up

Six, [extra meal]

To follow up