Hello, today I’m going to share with you Spring MVC. Take out your little notebook and write it down

Spring MVC Overview:

Model1: early Java Web development, the unified display layer, control layer, data layer of all operations to JSP or JavaBean to process

There is heavy coupling between JSPS and Java beans, and Java code and HTML code are also coupled together

Developers are required not only to master Java, but also to have advanced front-end skills

The front end and the back end depend on each other. The front end needs to wait for the back end to complete, and the back end also depends on the front end to complete in order to conduct effective testing

Code is hard to reuse

Model2 time: Those who have learned Servlet and done relevant Demo should understand the development mode of “Java Bean(Model)+ JSP (View,)+ Servlet (Controller)”, which is the early JavaWeb MVC development mode. Model: Data involved in the system, namely DAOs and beans. View: Shows the data in the model, just for presentation. Controller: Handles all user requests sent to, returns data to the JSP and presents it to the user.

[Img-wlybiv8K-1624972406397)(./Java project. Assets /model2.png)]

There are still many problems in Model2 mode. The degree of abstraction and encapsulation of Model2 is far from enough. When developing with Model2, it is inevitable to repeat the wheel, which greatly reduces the maintainability and reusability of the program. As a result, many MVC frameworks related to JavaWeb development emerged, such as Struts2, but Struts2 is cumbersome. With the popularity of Spring lightweight development frameworks, Spring MVC framework emerged in the Spring ecosystem, and Spring MVC is the best MVC framework currently available. Compared to Struts2, Spring MVC is simpler and more convenient to use, more efficient to develop, and faster to run.

MVC is a design pattern, and Spring MVC is an excellent MVC framework. Spring MVC can help us develop a cleaner Web layer, and it is inherently integrated with the Spring framework. Under Spring MVC, we generally divide back-end projects into Service layer (processing business), Dao layer (database operation), Entity layer (Entity class), and Controller layer (control layer, returning data to the front page).

Process Description (Important) :

The client (browser) sends the request directly to the DispatcherServlet.

The DispatcherServlet invokes HandlerMapping according to the request information and parses the Handler corresponding to the request.

After parsing to the corresponding Handler (commonly known as the Controller Controller), it is processed by the HandlerAdapter adapter.

The HandlerAdapter calls the actual Handler from the Handler to handle the request and the corresponding business logic.

After processing the business, the processor returns a ModelAndView object, Model is the returned data object, and View is a logical View.

The ViewResolver finds the actual View based on the logical View.

The DispaterServlet passes the returned Model to the View (View rendering).

Return the View to the requester (browser)

1. What is SpringMVC?

SpringMVC is a lightweight Java-based request-driven Web framework that implements the MVC design model and is a module of the Spring framework.

It uses a set of annotations to make a simple Java class a controller for handling requests without implementing any interfaces. It also supports RESTful programming style requests.

What is the MVC pattern?

The full name of MVC is Model View Controller, which is the abbreviation of Model – View – Controller. It is a Model of software design. It uses a method of separating business logic, data and interface display to organize the code, and gathers a large number of business logic into one part. When the interface and user interaction need to be improved and customized, there is no need to rewrite the business logic, so as to reduce the coding time.

V stands for View. A View is the interface that the user sees and interacts with. For example, a web page interface consisting of HTML elements, or a software client interface. One of the nice things about MVC is that it can handle many different views for your application. There’s no real processing going on in the view, it’s just a way to output data and allow the user to manipulate it.

M stands for Model. Models represent business rules. Of the three parts of MVC, the model has the most processing tasks. The data returned by the model is neutral and the model is independent of the data format, so that a model can provide data for multiple views, reducing code duplication because code applied to the model can be written once and reused by multiple views.

C stands for Controller. A controller is a controller that accepts input from the user and invokes models and views to fulfill the user’s requirements. The controller itself does not output anything or do any processing. It simply receives the request, decides which model artifact to call to process the request, and then determines which view to use to display the returned data.

3. SpringMVC execution process?

The user clicks on a request path and initiates a request, which is processed by the front-end controller.

The front-end controller asks the processor mapper to find the Handler. You can look it up by annotation or XML configuration.

The processor mapper finds the corresponding Handler(which may contain several Interceptor interceptors) based on the configuration and returns it to the front-end controller.

The front-end Controller requests the processor adapter to execute the corresponding Handler Handler (often called a Controller).

The processor adapter executes the Handler Handler.

The Handler Handler returns a ModelAndView object (the SpringMVC underlying object, including the Model data Model and View information) to the processor adapter upon completion of execution.

The processor adapter receives the ModelAndView returned by the Handler Handler and returns it to the front-end controller.

When the front controller receives the ModelAndView, it requests the ViewResolver to parse the view.

According to the View information, the View parser matches the corresponding View result and feeds it back to the front-end controller.

After receiving the specific View of the View, the front-end controller renders the View, fills the Model data in the Model into the Request field in the View View, and generates the final View.

The front-end controller returns the request results to the user.

4. What are the advantages of SpringMVC?

SpringMVC itself is integrated with the Spring framework and has both the benefits of Spring (such as dependency injection DI and aspect programming AOP).

SpringMVC provides powerful convention over configuration programming by contract support, providing a way to design software that reduces the number of decisions a software developer has to make to specify only the parts of an application that don’t conform to convention.

Flexible URL-to-page controller mapping is supported.

Easy integration with other view technologies (JSP, FreeMarker, and so on). Because SpringMVC’s model data tends to be placed in Map data structures, it can be easily referenced by other frameworks.

Has a very concise exception handling mechanism.

Data validation, formatting, and data binding mechanisms can be implemented flexibly, and data binding operations can be performed using any object.

RestFul style is supported.

What are the main components of Spring MVC?

Front-end controller DispatcherServlet:

Its purpose is to receive the user’s request and then give the user feedback on the result. As a repeater or central processor, it controls the execution of the whole process and uniformly schedules each component to reduce the coupling between components and facilitate the expansion of components. Handle all HTTP requests and responses.

HandlerMapping:

It is used to find matching processor information based on the requested URL path through annotations or XML configuration.

HandlerAdapter:

Its purpose is to execute relevant handlers according to specific rules based on the processor information found by the mapper processor.

Handler:

It performs the relevant request processing logic and returns the corresponding data and view information encapsulated in a ModelAndView object.

ViewResolver:

It is used to parse the View, resolving the logical View name into the real View View through the View information in the ModelAndView object (such as returning a real JSP page through a JSP path).

View the View:

A View is an interface, and the implementation classes support different View types (JSP, FreeMarker, Excel, and so on).

What are the differences between SpringMVC and Struts2?

The biggest difference is that Struts2 is much heavier than SpringMVC.

For SpringMVC entry is a Servlet, which is the front controller (DispatcherServlet), and the entry of the struts 2 is a Filter (StrutsPrepareAndExecuteFilter).

SpringMVC is method-based development (one URL for one method), request parameters are passed to method parameters, and can be designed as singletons or multiple (recommended singletons). Struts2 is class-based, with request parameters passed to the class’s member attributes, and can only be designed for multiple cases.

SpringMVC parses the request content through the parameter parser, assigns values to method parameters, encapsulates data and views into ModelAndView objects, and finally transfers the model data in ModelAndView to the page through requES domain. The Jsp view parser uses JSTL by default. Struts2 uses value stacks to store request and response data, and OGNL accesses the data.

7. How does SpringMVC set redirection and request forwarding?

Let’s talk about the difference between request forwarding and redirection:

Difference between request forwarding and redirection:

Request forwarding is done on the server side; The redirection is done on the client side.

Fast request forwarding speed; The redirection speed is slow.

Requests forward the same request; Redirects are two different requests.

Request forwarding does not execute the forwarded code; The redirect executes the code after the redirect.

The request forwarding address bar has not changed; The redirection address bar has changed.

Request forwarding must be done on the same server; Redirects can be done on different servers.

SpringMVC sets request forwarding:

Prefix the return value with “forward:”.

SpringMVC sets redirection:

Prefix the return value with “redirect:”. For example, when we log in, the login failure will be redirected to the login page.

8. What happens when a method returns special objects to AJAX, such as Object,List, etc.?

Annotate the method ** @responseBody ** to indicate that the method’s return value, regardless of type, will return JSON data.

Replace the @Controller annotation on the Controller class with the ** @restController annotation **.

@restController = @Controller + @responseBody indicates that all methods of the Controller class return data in JSON format (except those without @requestMapping annotations).

The @responseBody annotation returns JSON data because SpringMVC’s HttpMessageConverter automatically converts to JSON,

If Jackson or Gson is used, no additional configuration is required to automatically return JSON because the framework provides the corresponding HttpMessageConverter.

Join Jackson. The jar

Configure the JSON mapping in the configuration file

An Ajax method can return an Object, a List, etc., with the @responseBody annotation in front of it.

If you use Alibaba’s Fastjson, you’ll need to manually provide an instance of the corresponding HttpMessageConverter.

9. Common comments for SpringMVC:

Annotations are essentially a special interface that inherits annotations, implemented by JDK dynamic proxy classes.

When we fetch annotations through reflection, we also return dynamic proxy objects generated by the Java runtime.

Through a proxy object call the custom annotation method, will eventually call AnnotationInvocationHandler invoke method, this method will query from memberValues this Map out the value of the corresponding Java and memberValues source is constant pool.

1. @ Controller

@Controller is used to mark a class, and the class it marks is a SpringMVC Controller object. The processor adapter will scan the method of the class that uses the annotation and check if the method uses the @RequestMapping annotation. @Controller just defines a Controller class, and methods using the @RequestMapping annotation are the handlers that actually handle requests.

2, @ RequsestMapping

RequestMapping is an annotation that handles request address mapping, which can be used on a class or method.

Used on a class, this address is used as the parent path for all methods in the class that respond to requests. Return value will be through the view parser resolves to the actual physical view, for the InternalResourceViewResolver view parser, through the prefix + returnValue + suffix this way to get the actual physical view, and then do the forwarding operation.

Write in the method:

@requestMapping (“/req”) indicates that request types are not differentiated.

@requestMapping (value = “/req”,method = requestMethod. POST) indicates that this is a POST request.

3, @ ResponseBody

@responseBody converts a Java object into a JSON object, which is used for asynchronous Ajax requests that return jSON-formatted data instead of a page.

@RequestBody: Annotation implementation receives JSON data from HTTP requests and converts json to Java objects.

4, @ Valid

Flag parameters are validated by hibernate-Validator validation framework.

5, @ PathVariable

@pathvariable is used to receive parameters from URI addresses. One or more {Xxx} placeholders can be mapped in URLS. Placeholder parameters can be bound to method parameters through @pathvariable, which is often used in RestFul interface styles.

For example, the request URL: http://localhost/user/21/ zhang SAN/query

(Long can be changed to String or int as required, SpringMVC automatically converts it)

6, @ RequestParam

RequestParam is used to map request parameters to controller method parameters with the following three properties:

7, @ ControllerAdvice

@controllerAdvice Identifies a class as a global exception handler.

8, @ ExceptionHandler

ExceptionHandler Identifies a method for global exception handling.

Add: How the front end passes parameters to the Controller:

Write the form parameters directly into the parameters of the Controller’s corresponding methods

public String addUser(String username,String password) {}

2. Receive via HttpServletRequest

public String addUser(HttpServletRequest request) {

3. Receive via a bean

public String addUser(UserModel user) {

4. Use the ** @modelAttribute annotation ** to get the FORM data for the POST request

@RequestMapping(value=”/addUser”,method=RequestMethod.POST)

public String addUser(@ModelAttribute(“user”) UserModel user) {

Bind request parameters to method input parameters with the @requestParam annotation

An exception occurs when the request parameter username does not exist, which can be resolved by setting the attribute required=false,

For example: @requestParam (value= “username”, required=false)

@RequestMapping(value=”/addUser”,method=RequestMethod.GET)

public String addUser(@RequestParam(“username”) String username,@RequestParam(“password”) String password) {

Request. GetQueryString () to get spring MVC get request parameters

10, how to solve the POST request Chinese garble problem, and how to handle GET?

JavaWeb garble problems are generally caused by the inconsistency between the character sets of the client (browser) and the server. If the character sets of the client (browser) and the server are consistent, garble problems will not occur.

Resolve POST request garbled characters:

SpringMVC provides a filter to resolve POST request garble by default, which can be configured in web.xml

Resolve get request garble:

Modify the code of the Tomcat configuration file to be consistent with the project code.

<ConnectorURIEncoding=” UTF-8 “connectionTimeout=”20000″ port=”8080″ protocol=”HTTP/1.1” redirectPort=”8443″/>

2. Re-encode the request parameters. Iso8859-1 is the default Tomcat encoding.

String userName = new String(request.getParamter(“userName”).getBytes(“ISO8859-1″),”utf-8”);

Spring MVC exception handling?

For all kinds of predictable and unpredictable exceptions encountered in daily development, SpringBoot can be solved by the following three ways:

1. Use the @ExceptionHandler annotation

The front end sends a request to the back end. When an exception occurs, the back end can notify the front end in three ways: 1. Return an exception page without error information; 2. 2. Return ModelAndView, return view and exception information; 3. Return data in JSON format.

Disadvantages: Cannot implement global exception handling; The exception handling method must be in the same Controller as the error method.

2. Implement HandlerExceptionResolver interface

Can achieve global exception control, as long as the system is running exceptions, it will catch.

To implement this interface, you must override the resolveException method, which is the exception handling logic and can only return ModelAndView objects.

3. Use the @ControllerAdvice + @ExceptionHandler annotation

1. When code is added to @ControllerAdvice, it does not need to be in the same Controller.

2. @ControllerAdvice +@ExceptionHandler can also implement global exception catching.

3. Different types of exceptions are handled by different exception processing methods.

SpringBoot does not support catching 404 exceptions by default. You need to add the following two configurations for catching 404 exceptions to take effect.

12, SpringMVC controller is a singleton pattern, what is the problem, how to solve?

Controller is a singleton mode, which may cause thread safety problems when multi-threaded access. Do not use synchronization, which will affect program performance.

The solution is that you can’t write mutable state quantities in your controller.

If you need to use these mutable state quantities, you can use ThreadLocal, which creates a separate copy for each thread and operates independently of each other.

13. If you want to intercept methods submitted by get in a request interception, how to configure it?

You can add method= requestMethod.get to @requestMapping.

Use the @getMapping annotation.

@GetMapping(value=”/toLogin”)

public ModelAndView toLogin(){}

How do I get request or session from a controller method?

Declare request, session, and SpringMvc automatically inject them by declaring them directly in the parameters of the controller method.

15. If you want to get an argument passed from the foreground in an intercepting method, how do you get it?

Declare this parameter in the parameter of the controller method, but the name must be the same as the passed parameter name, otherwise the parameter mapping fails. The userId in the method parameter below receives a value from the front with the parameter name userId.

16, the foreground passed multiple parameters, and these parameters are attributes of an object, how to bind parameters?

Simply declare the parameter in the controller method’s parameter, and SpringMVC will automatically request that the parameter be assigned to the object’s properties.

The user in the following method parameter is used to receive multiple parameters from the front end. The parameter name needs to be the same as the user entity class attribute name.

Front-end parameter query in Demo project:

Controller:

Service:

ServiceImpl:

Mapper: — [named parameters] : specifies the encapsulation parameters explicitly — @param annotation

Mapper.xml:

Parameter binding in SpringMVC

The default binding types supported by SpringMVC are:

HttpServletReequest object: Parameter information can be obtained from the Request object

HttpservletResponse object: Response information can be processed through the Response object

HTTPSession object: Gets the object stored in the session

Model/ModelMap: Model is an interface, and ModelMap is an implementation of the interface. Populates the model data into the Request field.

During parameter binding, if the above type is encountered, it is directly bound. That is, we can define these types of parameters directly in the controller’s method parameters, and SpringMVC will bind them automatically. The Model/ModelMap object is an interface, and ModelMap is an interface implementation that populates the Model data into the Request field, similar to ModelAndView.

TODO: Collection type bindings wait

What is the return value of a SpringMVC function?

Summary of the four return value types of SpringMVC

1, ModelAndView

In SpringMVC, the ModelAndView type is often returned; After the front and back ends are separated, the back end returns the JSON format.

The ModelAndView type can specify a view name or bind data

2, void

1. There is no return value in the method, SpringMVC will resolve the name as the view name by default. If the view exists, an exception is reported.

You can also return empty JSON data by annotating @responseBody.

2. Request forwarding

3. Implement redirection

3, the String

1. “userList” — Mandatory String Most commonly returns a logical view name, in which case the default parameter Model is used to pass data.

2. “Redirect :tologin” — Redirection: redirects to the login page if the login fails.

3. “Forward :tologin” — Request forwarding: requests to be forwarded to the login page if the login fails.

4. “You’re great!” — True returns String, equivalent to JSON data.

4, JSON

If Jackson or Gson is used, the HttpMessageConverter automatically converts the data to JSON. If Jackson or Gson is used, No extra configuration is required to automatically return JSON, because the framework provides the corresponding HttpMessageConverter for us. If we use Alibaba Fastjson, we need to manually provide an instance of the corresponding HttpMessageConverter.

What object does SpringMVC use to pass data from the background to the front desk?

1. Use Map, Model, and ModelMap methods, which store data in the Request domain

2. Use request

3. Use ModelAndView

19. SpringMVC has a class that combines views with data. What is it called?

Is the ModelAndView.

Use the ModelAndView class to store the resulting data after processing, as well as the view that displays the data. The name “Model” in ModelAndView represents the Model and “View” represents the View, which explains the purpose of this class. After the Controller processor calls the model layer to process the user request, it stores the result data in the model property of the class, stores the view information to be returned in the View property of the class, and then returns the ModelAndView to the front-end Controller. The front-end controller parses the object by calling the view parser defined in the configuration file, and finally displays the resulting data on the specified page.

Return to specified page

The ModelAndView constructor can specify the name of the page to return.

You can also jump to the specified page using the setViewName() method.

Return the desired value

Use addObject() to set the value that needs to be returned. AddObject () has methods with several different parameters that can default to and specify the name of the returned object.

20. How to put ModelMap data into session?

Add the @sessionAttributes annotation to the class to store the specified Model data into the session.

@SessionAttributes

By default, Spring MVC stores the data in the model into the Request domain. When a request ends, the data is invalidated.

If you want to use it across pages, you need to use sessions. The ** @sessionAttributes annotation makes a copy of the data in the model stored in the session field. 支那

SessionAttributes can only be defined in Class and interface enum. The @sessionAttributes function adds key/value pairs from the specified Model to a session for use within a session.

@ SessionAttributes parameters:

Names: This is an array of strings. It should contain the name of the data to be stored in the session.

Types: Stores parameters of the corresponding type in the model into the session according to the specified parameter type.

Value: The same as names above.

In the code above, add the @sessionAttributes annotation to the class and specify that Model data with names and type Integer be stored in the Session field.

21. How is the interceptor written in SpringMVC?

SpringMVC interceptors can be used for authentication and authorization operations in the following scenarios: login authentication interceptor (mall), character filtering interceptor, log operation interceptor, and so on.

SpringMVC interceptors are generally implemented in one of two ways:

The custom Interceptor class implements Spring’s HandlerInterceptor interface.

Inherited implementation HandlerInterceptor interface classes, such as Spring already provided the implementation of the abstract class HandlerInterceptorAdapter HandlerInterceptor interface.

The HandlerInterceptor interface defines three methods that are used to intercept user requests.

PreHandle () :

This method is called before the Controller processes the request. The SpringMVC Interceptor is called in a chain, 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 Controller method processes the current request and is called before the DispatcherServlet renders the view return, so the ModelAndView object after the Controller process can be manipulated in this method. — Mostly used to process returned views.

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 executed only when the corresponding Interceptor’s preHandle method returns 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. — Suitable for some resource cleaning and recording

Method execution rules in multiple interceptors:

Multiple interceptors can be configured, with three methods in each interceptor. The method execution patterns in multiple interceptors are summarized below.

PreHandle: The Controller method is executed before processing the request, forward, in the order defined by the interceptor.

PostHandle: The Controller method executes after processing the request, in reverse order as defined by the interceptor. Called only if all preHandle methods return true.

AfterCompletion: Execute the View in reverse order as defined by the interceptor. PreHandle returns true.

Interceptors in my project

Then define the annotation in LoginRequired:

Specific call:

@RequestMapping(“checkCart”)

@LoginRequired(loginSuccess = false)

// Check the cart, return to the cart’s inline page – a small page, Ajax asynchronous + inline page – refresh the inline page

public String checkCart(String isChecked, String skuId, HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap modelMap)

Well, this is the end of today’s article, I hope to help you confused in front of the screen