Search code examples
springrestspring-mvcserializationmodelandview

Does ModelAndView serialize model before sending response to client


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?


Solution

  • 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.