0

In spring mvc, when we return ModelAndView / Model object, does this get serialized to be sent on HTTP? Just like it happens in REST API that the @ResponseBody annotated method returned value is serialized. If not, how is Model object transferred over HTTP in Spring MVC as I have read that objects can't be transferred over HTTP without serialization?

1 Answers1

2

It depends. It depends on the view technology in use. But for most they will be exposed as request attributes and that is done in the View. The AbstractView has code for this which is used by most View implementations.

For something like Freemarker the model is exposed both as request attributes but also added to the Freemarker internal model object. This is so that Freemarker can render the page and you could also use tags in the template to retrieve the request attributes.

Depending on the actual view technology used if something gets serialized depends. For things generating HTML, PDF, Excel etc. nothing will be serialized. All the rendering and processing is done on the server and the end result (the complete view) is being sent to the client.

However, for view technologies like the MappingJackson2JsonView (there are others as well) that will actually serialize the model using Jackson. But in the end, this will be JSON that is sent over HTTP.

So what is sent over HTTP is at least never the actual model but depends on the view technology in use.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • So is spring model serialized or not during data transfer to client ? Because as far as I have read, objects can't be transferred over HTTP without serialization? – Shweta Priyadarshani Feb 03 '22 at 10:02
  • 1
    Nothing is serialized as nothing is send over HTTP but HTML. When using ModelAndView the end result is HTML. So everything is on the server. – M. Deinum Feb 03 '22 at 10:08
  • Ok , so is my understanding correct - when we use @ResponseBody , then data is sent over HTTP while when we use ModelAndView , data/model is sent to our view page in HTML format ? – Shweta Priyadarshani Feb 03 '22 at 10:16
  • 1
    That depends on the view technology in use (as I stated in my updated answer). Which is still a bit incomplete as JSON is also a representation, you could even use a `MappingJackson2JsonView` which will actually do serialize the model (the `Map` I mentioned earlier) using Jackson. – M. Deinum Feb 03 '22 at 10:32