Tell me about the execution order of @ ModelAttribute in parent class and subclass

  • 2021-09-20 20:23:16
  • OfStack

@ ModelAttribute Execution Order in Parent and Subclass

Methods annotated with @ ModelAttribute are executed before each Controller method is executed, so use caution when one Controller contains multiple URL.

Execution sequence:

Execute the @ ModelAttribute annotated method of the subclass first, and then execute the @ ModelAttribute annotated method of the parent class.

Overview of @ ModelAttribute principle and points for attention in use

@ ModelAttribute annotation modification method:

1. Take out the object from the database and put it into Map with the key user

2. SpringMvc takes the User object from the Map and assigns the request parameter to the corresponding attribute of the User object

3. SpringMvc passes the above object into the parameters of the target method

Note: In the @ ModelAttribute modified method, the key name put into Map should be matched with the lowercase string 1 of the first letter of the parameter type of the target method

Source code analysis process:

Calling the @ ModelAttribute annotation-decorated method, the data in Map in the @ ModelAttribute method is actually placed in implicitModel.

Parses the target parameter of the request processor, which actually comes from the target attribute of the WebDataBinder object

1). Create an WebDataBinder object

Determine the objectName attribute: If the passed attrName attribute value is ", objectName is lowercase for the first letter of the class name

Note: attrName If the POJO attribute of the target method is modified with @ ModelAttribute, the value of attrName is the value attribute of @ ModelAttribute

Determine the target attribute

Find the attribute value corresponding to attrName in implitModel. If it does not exist, verify whether the current handler is decorated with @ sessionAttribute, and try to get the attribute value corresponding to attrName from session. If it does not exist in session, an exception is thrown.

If Handler is not decorated with @ sessionAttribute, or if there are no key and attrName phases specified by the value value in @ SessionAttrbutes, an POJO object is created by reflection.

2). SpringMvc assigns the request parameters of the form to the corresponding attributes of target of WebDataBinder,

3). SpringMvc will give attrName and targe of WebDataBinder to implicitMoel

4). Pass target of WebDataBinder as a parameter to the target method's entry parameter


Related articles: