Points to note when using @SessionAttributes in Spring boot

In Spring Boot, if you want to save data in the session, of course, you can use the native Request to save the session directly. There is a more convenient way to use the annotation @SessionAttributes.

To use this annotation, you need to figure out how it works, that is, when to save and when to take it out, otherwise you will be confused when you get unexpected results.

Especially when mixed with the annotation @ModelAttribute, you need to figure out the priority.

 

1. Save the session.

   When the @SessionAttributes annotation is used in a Controller class, after the handler is executed, the data specified in the model will be saved to the session.

   Due to the timing of execution, when mixed with the annotation @ResponseBody, an error will occur.

   Using the @ResponseBody annotation, when returning an entity class, the ReturnValueHandler uses the RequestResponseBodyMethodProcessor, which directly writes the result to the response internally, and then closes it.

   Then, if you write data into the session, you can't write it in.

   The solution is to return a MappingJackson2JsonView instance directly without annotating @ResponseBody.

 

2. Session reading

   If @SessionAttributes is also used in a Controller class, there is a data binding method that uses @ModelAttribute, and a request handler parameter that uses @ModelAttribute.

   First read the session, if the session has no value, then execute the method of binding data, and then bind the request data

   First read the session, if the session has a value, then skip the method of binding data, and then bind the request data

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326399565&siteId=291194637