Memory usage of @ModelAttribute and @SessionAttributes


April 2019


252 time


I am doing Spring web application. I have a form and need to load a form object in form GET and POST. I have two ways of loading the object:

  1. Load the object via @ModelAttribute annotated on a method

  2. Load the object via the form's GET method and annotate the form controller with @SessionAttributes({"command"})

My question is:

Is it a good idea to use the @ModelAttribute approach for a web application with a large number of simultaneous online users? Can it make a difference?

1 answers


Comparison of @ModelAttribute vs @SessionAttributes is really an architectural judgment, ie: stateful vs stateless.

There is a third option to store the state in the form. This means when submit is clicked, the data loaded in the initial get method is sent in the post, so it doesn't need to be reloaded.

And a fourth option to store in cookies.

There are many issues to consider once using sessions:

  • in load balanced architecture, how are sessions sent between servers, or is user kept to only one server (sticky sessions)
  • what happens if a server is restarted (persistent session)?
  • when does session expire and what happens when it expires?

Even if you have the architecture in place to manage the sessions, there use should be kept to a minimum as they require system memory, whereas state stored in a database only requires disk space, and state stored on the client only requires client memory.

There is also security to consider, state stored on the server is more secure than state stored on client side.