springMVC face-to-face

1. What is MVC?

insert image description here

The user's request will reach the Servlet, and then call the corresponding Java Bean according to the request, and hand over all the display results to JSP for completion. This mode is called MVC mode.

MVC is a design pattern in which the software is divided into three layers, namely Model (model), View (view), and Controller (controller). Model represents data, View represents user interface, and Controller represents data processing logic, which is the bridge between Model and View. The advantage of layering software is that it can reduce the coupling between objects and facilitate code maintenance.
MVC is a software architecture idea that divides software into models, views, and controllers.

M: Model, model layer, refers to the JavaBean in the project, the role is to process data dao, bean

JavaBean is divided into two categories:

One class is called Entity Class Bean: it stores business data specially, such as Student, User, etc.
One class is called Business Processing Bean: it refers to Service or Dao object, which is specially used to process business logic and data access.

V: View, view layer, refers to pages such as html or jsp in the project, which is used to interact with users and display data

C: Controller, control layer, refers to the servlet in the project, the role is to receive requests and respond to browsers

The workflow of MVC:

The user sends a request to the server through the view layer, the request is received by the controller in the server, the controller calls the corresponding model layer to process the request, and returns the result to the controller after processing, the controller then finds the corresponding view according to the result of the request processing, and renders the data The final response to the browser

1.1 What is Spring MVC

Spring MVC is a Java-based lightweight web framework that implements the request-driven type of the MVC design pattern. By separating the Model, View, and Controller, it decouples the responsibility of the web layer and divides complex web applications into logically clear sections. part, simplify development, reduce errors, and facilitate cooperation among developers in the group

SpringMVC is a follow-up product of Spring and a sub-project of Spring

SpringMVC is a complete set of solutions provided by Spring for the development of presentation layer. After the presentation layer framework has undergone successive changes in many products such as Strut, WebWork, and Strut2, the industry generally chooses SpringMVC as the preferred solution for the development of the presentation layer of Java EE projects.

Note: The three-tier architecture is divided into presentation layer (or presentation layer), business logic layer, and data access layer. The presentation layer represents the foreground page and background servlet

1.2 Features of Spring MVC

  • Native products of the Spring family , seamlessly interface with infrastructure such as IOC containers
  • Based on the native Servlet , through the powerful front controller DispatcherServlet , the request and response are processed uniformly
  • The problems that need to be solved in each segment of the presentation layer are covered in an all-round way , and comprehensive solutions are provided
  • The code is fresh and concise , greatly improving development efficiency
  • The degree of internal componentization is high, and the pluggable components can be plugged and played . You can configure the corresponding components for any function you want.
  • Excellent performance , especially suitable for the requirements of modern large-scale and ultra-large Internet projects

2. What does the DAO layer do?

DAO is the abbreviation of Data Access Object, that is, data access object. In the project, it is usually used as an independent layer, dedicated to accessing the database. There are many specific implementation technologies of this layer, such as Spring JDBC, Hibernate, JPA, MyBatis, etc. are commonly used. No matter which technology is used to access the database under the Spring framework, its programming mode is unified.

3. Introduce the execution process of Spring MVC

  • The whole process starts with an HTTP request from the client, which is received by the web application server. If the request mapping path of DispatcherServlet is matched, the web container will forward the request to DispatcherServlet for processing.

  • After DispatcherServlet receives this request, it will find the processor (Handler) that processes the request according to the requested information (including URL, HTTP method, request header, request parameters, Cookie, etc.) and the configuration of HandlerMapping. HandlerMapping can be regarded as a routing controller, and Handler can be regarded as a target host. It is worth noting that a Handler interface is not defined in Spring MVC. In fact, any Object can become a request handler.

  • When the DispatcherServlet obtains the Handler corresponding to the current request according to the HandlerMapping, it encapsulates the Handler through the HandlerAdapter, and then calls the Handler with a unified adapter interface. HandlerAdapter is a Spring MVC framework-level interface. As the name suggests, HandlerAdapter is an adapter that uses a unified interface to call various Handler methods.

  • After the processor completes the processing of the business logic, it will return a ModelAndView to the DispatcherServlet. The ModelAndView contains the logical name of the view and the model data information.

  • What ModelAndView contains is a "logical view name" rather than a real view object. DispatcherServlet uses ViewResolver to complete the parsing work from the logical view name to the real view object.

  • After obtaining the real view object View, DispatcherServlet uses this View object to render the model data in ModelAndView.

  • The final response message obtained by the client may be an ordinary HTML page, an XML or JSON string, or even a picture or a PDF document and other different media forms.

4. Talk about the Spring MVC annotations you know

  • @RequestMapping:

    Function: The function of this annotation is to process the request address mapping, that is to say, map the processor method to the url path.

    Attributes:

    method: It allows you to specify the method type of the request, such as get and post, which are commonly used.

    value: refers to the actual address of the request, if there are multiple addresses, just use {} to specify it.

    produces: Specifies the returned content type, which can only be returned when the Accept type in the request header contains the specified type.

    consumes: Specifies the submitted content type for processing requests, such as some types of json, html, text, etc.

    headers: When specifying that the header value must be included in the request, it will use this method to process the request.

    params: Specify the parameter values ​​that must be included in the request, and it will use this method to process the request.

  • @RequestParam:

    Function: It is to bind the request parameters to the method parameters of your controller, and it is the annotation for receiving ordinary parameters in Spring MVC.

    Attributes:

    value is the name in the request parameter.

    required is whether the request parameter must provide parameters, and its default is true, which means that it must be provided.

  • @RequestBody:

    Function: If it acts on the method, it means that the return result of the method is directly written into the Http response body (annotation generally used when obtaining data asynchronously).

    Attribute: required, whether there must be a request body. Its default value is true. When using this annotation, it is worth noting that when it is true, the get request method will report an error. If you set the value to false, the get request method will be null.

  • @PathVariable:

    Function: This annotation is used to bind the placeholder in the url, but note that after spring3.0, the url began to support the placeholder, which is an important symbol of the rest-style url supported by Spring MVC.

5. Introduce the interceptor of Spring MVC

The interceptor intercepts the processor, so that the function of the processor can be enhanced through the interceptor. In Spring MVC, all interceptors need to implement the HandlerInterceptor interface, which contains the following three methods: preHandle(), postHandle(), and afterCompletion().

The execution flow of these methods is as follows:
insert image description here

  • As can be seen from the above figure, the execution flow of the Spring MVC interceptor is as follows:

    Execute the preHandle method, which returns a boolean value. If false, end all processes, if true, execute the next step.

    Executes the processor logic, which contains the functionality of the controller.

    Execute the postHandle method.

    Perform view resolution and view rendering.

    Execute the afterCompletion method.

  • The development steps of the Spring MVC interceptor are as follows:

    Develop interceptors:

      实现handlerInterceptor接口,从三个方法中选择合适的方法,实现拦截时要执行的具体业务逻辑。
    

    Register interceptor:

      定义配置类,并让它实现WebMvcConfigurer接口,在接口的addInterceptors方法中,
      注册拦截器,并定义该拦截器匹配哪些请求路径。
    

6. How to do request interception?

reference answer

If it is to intercept the Controller memory, you can use the Spring MVC interceptor.

If you want to intercept all requests (such as requests to access static resources), you can use Filter.

If you are intercepting requests from beans other than the Controller, you can use Spring AOP.

Replenish

1. The difference between forwarding and redirection

The difference between forwarding and redirection and how to use it (full)

The view in SpringMVC is the View interface. The function of the view is to render data and display the data in the model to the user.

There are many types of SpringMVC views, and there are forwarding views and redirecting views by default.

  • Forwarding is a request, the first time is sent by the browser (the second time is inside the server), we are talking about a request sent by the browser. (Because the second time happened inside the server, the forwarded address bar is still the address bar of the first request)

  • Redirection is two requests, the first is to access the servlet, and the second is to access the redirected address. (The final address bar address is the redirected address)

  • Forwarding can obtain data in the request domain, but redirection is not, because forwarding is a request, and the request used is the same.
    Redirect the browser to send two requests, and the two requests are two request objects

  • Forwarding can access objects in web-inf, but redirection cannot, because web-inf has security and can only be accessed through the server, not through the browser

  • Forwarding cannot cross domains, but redirection can. Cross-domain means that forwarding occurs inside the server, and only resources inside the server can be accessed. Redirection can access external resources, such as redirection to Baidu

1.1、ThymeleafView

When the view name set in the controller method does not have any prefix, the view name at this time will be parsed by the view resolver configured in the SpringMVC configuration file, and the final path obtained by splicing the view name with the view prefix and view suffix will pass The forwarding method realizes the jump

1.2. Forward view (rarely used) -- prefix "forward:"

The default forwarding view in SpringMVC is InternalResourceView

The situation of creating forwarding view in SpringMVC:

When the view name set in the controller method "forward:"is prefixed, the InternalResourceView view is created. At this time, the view name will not be parsed by the view resolver configured in the SpringMVC configuration file, but the prefix "forward:" will be removed. The remaining part is used as the final path to realize the jump by forwarding

For example "forward:/", "forward:/employee"

<a th:href="@{/testForward}">测试InternalResourceView</a><br>
@RequestMapping("/testForward")
    public String testForward(){
    
    
        return "forward:/testThymeleafView";
    }

1.3. Redirect view (used a lot) -- prefix "redirect:"

The default redirection view in SpringMVC is RedirectView

When the view name set in the controller method "redirect:"is prefixed, create a RedirectView view. At this time, the view name will not be parsed by the view resolver configured in the SpringMVC configuration file, but the prefix "redirect:" will be removed. The remaining part is used as the final path to realize the jump through redirection

For example "redirect:/", redirect to the home page
"redirect:/employee"

<a th:href="@{/testRedirect}">测试RedirectView</a><br>
 @RequestMapping("/testRedirect")
    public String testRedirect(){
    
    
        return "redirect:/testThymeleafView";
    }

2. RESTful (a style of software architecture, that is, format)

It’s okay to use it, or it’s okay to not use it.
RESTFul from entry to proficiency in super full analysis (full)

1. Introduction to RESTful
REST: Representational State Transfer, resource state transfer at the presentation layer.

2. The implementation of RESTful
Specifically speaking, in the HTTP protocol, there are four verbs indicating the operation mode: GET, POST, PUT, DELETE.

They correspond to four basic operations: GET is used to obtain resources, POST is used to create new resources, PUT is used to update resources, and DELETE is used to delete resources.

The REST style advocates the use of a unified style design for the URL address. Each word is separated by a slash from front to back, and the request parameters are not carried in the form of question mark key-value pairs. Instead, the data to be sent to the server is used as a part of the URL address to ensure the overall style. consistency.
insert image description here

3、HiddenHttpMethodFilter

Since the browser only supports sending get and post requests, how to send put and delete requests?

SpringMVC provides HiddenHttpMethodFilter to help us convert POST requests into DELETE or PUT requests

HiddenHttpMethodFilter handles the conditions for put and delete requests:

a> The request method of the current request must be post

b>The current request must transmit the request parameter _method

If the above conditions are met, the HiddenHttpMethodFilter filter will convert the request method of the current request into the value of the request parameter _method, so the value of the request parameter _method is the final request method

<form th:action="@{/user}" method="post">  
    <input type="hidden" name="_method" value="PUT">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="修改"><br>
</form>
@RequestMapping(value = "/user", method = RequestMethod.PUT)
    public String updateUser(String username, String password){
    
    
        System.out.println("修改用户信息:"+username+","+password);
        return "success";
    }

4、HttpMessageConverter

HttpMessageConverter, a message information converter, converts a request message into a Java object, or converts a Java object into a response message

HttpMessageConverter provides two annotations and two types: @RequestBody, @ResponseBody, RequestEntity, ResponseEntity

HttpMessageConverter provides two annotations and two types:

@RequestBody,RequestEntity
@ResponseBody,ResponseEntity

@ResponseBody (used a lot) is used to identify the controller method
@ResponseBody is used to identify a controller method, and the return value of the method can be directly responded to the browser as the response body of the response message

<a th:href="@{/testResponseBody}">通过@ResponseBody响应浏览器数据</a><br>
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
    
    
    return "success"; //响应给浏览器的数据,也就是响应到浏览器的响应体

Result: The browser page displays success, and no longer jumps to the success.html page

4.1 Question raised: @ResponseBody directly responds to the error reported by the browser User object

Because it is not string data, the browser accepts the response data from the server must be in string format

4.2, SpringMVC processing json (solve 4.1 problem)

Note: Entity class, map converted to json is a json object, list converted to json is a json array

Steps for @ResponseBody to process json:

a> import jackson dependencies

b> Turn on the annotation driver of mvc in the core configuration file of SpringMVC. At this time, a message converter will be automatically assembled in the HandlerAdaptor: MappingJackson2HttpMessageConverter, which can convert the Java object responding to the browser into a string in Json format

<mvc:annotation-driven />

c> Use the @ResponseBody annotation on the processor method to identify

d> Return the Java object directly as the return value of the controller method, and it will be automatically converted to a string in Json format

@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
    
    
    return new User(1001,"admin","123456",23,"男");
}

The results displayed in the browser's page:

{“id”:1001,“username”:“admin”,“password”:“123456”,“age”:23,“sex”:“男”}

4.3, Spring MVC processing ajax

Ajax is to interact with the server without jumping the page

4.4, @RestController annotation

The @RestController annotation is a composite annotation provided by springMVC. It is marked on the controller class, which is equivalent to adding the @Controller annotation to the class, and adding the @ResponseBody annotation to each method in it.

4.5, ResponseEntity (used a lot)

ResponseEntity is used for the return value type of the controller method, and the return value of the controller method is the response message to the browser

5. Interceptor

Introduction
Controller controller (also called processor), after the controller method is called, it returns a unified Model and View object.

The interceptor intercepts the controller method. The three abstract methods of the interceptor are one before the execution of the controller method, one after the execution of the controller method, and one after the rendering of the view.

5.1. Interceptor configuration

Interceptors in SpringMVC are used to intercept the execution of controller methods

Interceptors in SpringMVC need to implement the HandlerInterceptor interface

The SpringMVC interceptor must be configured in the SpringMVC configuration file:

Note: A bean is a component in the ioc container, an object.

5.2. Three abstract methods of interceptors

Interceptors in SpringMVC have three abstract methods:

preHandle: Execute preHandle() before the controller method is executed, and its return value of boolean type indicates whether to intercept or release, return true to release, that is, call the controller method; return false to indicate interception, that is, not to call the controller method

postHandle: Execute postHandle() after the controller method is executed

afterComplation:After processing the view and model data, execute afterComplation() after rendering the view

5.3. If the preHandle() of each interceptor returns true

At this time, the execution order of multiple interceptors is related to the configuration order of the interceptors in the SpringMVC configuration file:

preHandle() will be executed in the order of configuration,
while postHandle() and afterComplation() will be executed in reverse order of configuration

5.4. If the preHandle() of an interceptor returns false

preHandle() returns false and preHandle() of its previous interceptor will be executed,
postHandle() will not be executed,
and afterComplation() of the interceptor before the interceptor returning false will be executed

If there are 5 interceptors, and now the third preHandle() is set to false, then preHandle() of interceptors 1, 2, and 3 will be executed; postHandle() will not be executed; afterComplation() of interceptor 2 will be executed

6. Exception handler

6.1. Configuration-based exception handling

SpringMVC provides an interface to handle exceptions that occur during the execution of controller methods: HandlerExceptionResolver

The implementation classes of the HandlerExceptionResolver interface are: DefaultHandlerExceptionResolver and SimpleMappingExceptionResolver

SpringMVC provides a custom exception handler SimpleMappingExceptionResolver,

6.2. Annotation-based exception handling

@ControllerAdvice identifies the current class as a component for exception handling. @ControllerAdvice and @component are almost the meaning of identifying components

@ExceptionHandler is used to set the exception handled by the identified method

ex indicates the exception object that occurs in the current request processing

//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
    
    

    //@ExceptionHandler用于设置所标识方法处理的异常
    @ExceptionHandler(ArithmeticException.class)
    //ex表示当前请求处理中出现的异常对象
    public String handleArithmeticException(Exception ex, Model model){
    
    
        model.addAttribute("ex", ex);
        return "error";
    }

}

7. The execution process of SpringMVC

insert image description here

Simple version of the process

1. The user sends a request to the front controller DispatcherServlet.

2. DispatcherServlet receives a request to call HandlerMapping processor mapper.

3. The processor mapper finds the specific processor (can be searched according to the xml configuration and annotation), and generates the processor object and processor

Interceptors (generated if any) are returned to DispatcherServlet.

4. DispatcherServlet calls HandlerAdapter processor adapter.

5. The HandlerAdapter calls a specific processor (Controller, also called a back-end controller) after adaptation.

6. After the execution of the Controller is completed, it returns to the ModelAndView.

7. HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet.

8. DispatcherServlet passes ModelAndView to ViewReslover view resolver.

9. ViewReslover returns a specific View after parsing.

10. DispatcherServlet renders the view according to the View (that is, fills the model data into the view).

11. DispatcherServlet responds to the user.

8. Common components of SpringMVC

  • DispatcherServlet: front-end controller , does not require engineers to develop, provided by the framework

Role: Unified processing of requests and responses, the center of the entire process control, which calls other components to process user requests

  • HandlerMapping: processor mapper , does not require engineers to develop, provided by the framework

Function: Find the Handler according to the requested url, method and other information, that is, the controller method

  • Handler: Processor , which needs to be developed by engineers

Function: Handler processes specific user requests under the control of DispatcherServlet

  • HandlerAdapter: Processor adapter , no need for engineer development, provided by the framework

Function: Execute the processor (controller method) through HandlerAdapter

  • ViewResolver: view resolver , no need for engineer development, provided by the framework

Function: Perform view analysis to obtain corresponding views, for example: ThymeleafView, InternalResourceView, RedirectView

  • View: view

Role: display the model data to the user through the page

9. DispatcherServlet initialization process

DispatcherServlet is essentially a Servlet, so it naturally follows the Servlet life cycle. So macroscopically, it is the Servlet life cycle to schedule.

a>Initialize the WebApplicationContext
b> create WebApplicationContext
c>DispatcherServlet initialization strategy

After the FrameworkServlet creates the WebApplicationContext, it refreshes the container and calls onRefresh(wac). This method is rewritten in the DispatcherServlet, and the initStrategies(context) method is called to initialize the strategy, that is, to initialize each component of the DispatcherServlet.

10. A detailed explanation of the eleven processing procedures of Spring MVC?

  1. The browser sends a request, who is the request sent to? Send to the front-end controller first, that is to say, all requests are sent to the front-end controller. The front-end controller is the entrance of all requests, but the front-end controller cannot handle business requests, it is just a request forwarding
  2. Who will handle business requests? Handler processor to actually process business requests, so the question is, how does the front controller find this Handler processor? What the processor mapper records is the mapping relationship between the requested url and the processing method. How is this mapping relationship established? It is established through the @RequestMapping annotation. This mapping relationship is equivalent to a Map (key-value form), the key is the requested url, and the value is the Handler for processing. Now, after the front controller gets this request, how to find the corresponding Handler? It is necessary to find the processor mapper and ask who it requests to handle it?
  3. The processor mapper will find the corresponding processor according to the url you requested. If it can’t find it, it will report an error. If it finds it, then it will return a processor execution chain. In this processor execution chain, there is Handler In addition, there are interceptors (here we can develop our own interceptors), and then return to the front controller
  4. The front controller still can't handle this business request. It has another thing to do at this time, because it returns the Handler, and it doesn't know what type the Handler is, because in springmvc, the Handler can be in the form of annotations, In fact, it can also be in the form of non-annotation (we generally don’t use the non-annotation form). The front controller does not know what type the Handler is, so there is no way to execute it, so it has to find something to execute, and then it will put This matter is handed over to another component for processing. This component is called a processor adapter. This processor adapter is used to adapt different types of Handlers. It will choose different types of adapters to execute it according to your different types of Handlers
  5. If the current Handler is in the form of annotation, then it will select the processor adapter in the form of annotation to execute the Handler. The Handler is executed, that is to say, the method in our Controller class is executed. After the method is executed, the business inside is processed
  6. After business processing, a ModelAndView is finally returned. It is useless for the processor adapter to get this result. Its function is to execute the Handler. After the Handler is executed, its work is done.
  7. After the completion, get the return result, then it will throw the return result to the front controller intact, and the work of the processor adapter is done at this time
  8. The front controller gets this ModelAndView, it still has no way to deal with it, it still can't return html, then it needs to find the corresponding jsp, because ModelAndView contains both the model and the view, and this view specifies who we want to use to render the data. We want to render data, then it needs to find a view parser to parse this view, because there are many kinds of this view (our most common view is jsp, in addition to jsp, there are actually others, for example, it can also be a report , it can also be pdf, it can also be freemaker, etc.), it will find different view parsers to process. Because now our most commonly used view is jsp, so it finds the view parser corresponding to jsp
  9. Find this view parser, it will parse this view, and it will return a View object after parsing
  10. Finally, we call the process of rendering the view of the view parser. The process of rendering the view is actually for our jsp, which is to render the data into html
  11. After the final rendering into html, it responds to the user

11. Is the controller of Spring MVC a singleton mode? What's the problem? How to deal with it?

It is a singleton pattern. So there are thread safety issues when accessing by multiple threads. Do not use synchronization, it will affect performance, the solution is not to write fields in the controller

12. What annotations are commonly used in Spring MVC?

@RequestMapping: An annotation for processing request url mapping, which can be used on classes or methods. When used on a class, it means that all methods of responding to requests in the class use this address as the parent path
@RequestBody: Annotation implements receiving json data of http requests and converts json to java objects
@ResponseBody: Annotation implements returning the conreoller method The object is converted into a json object and responded to the client

13. How to intercept the method submitted by get in the interception request?

Add method=RequestMethod.GET to the @RequestMapping annotation

14. How to get Request or Session in the method?

Declare request directly in the formal parameter of the method, and Spring MVC will automatically pass in the request object

15. How to get the parameters passed in from the foreground in the interception method?

Just declare this parameter directly in the formal parameter, but the name must be the same as the passed parameter

16. If many parameters are passed in at the foreground, and these parameters are all one object, how to get this object?

Just declare this object directly in the method, and Spring MVC will automatically assign properties to this object

17. What is the return value of a function in Spring MVC?

The return value can have many types, such as String, ModelAndView. ModelAndView combines views and data, but it is generally better to use String

18. How does Spring MVC implement an interceptor?

One is to implement the HandlerInterceptor interface, and the other is to inherit the adapter class

Guess you like

Origin blog.csdn.net/m0_50736744/article/details/126432842