Spring MVC

How does Spring MVC handle multiple users

https://stackoverflow.com/questions/17235794/how-does-spring-mvc-handle-multiple-users

Every web request generate a new thread. See How are Threads allocated to handle Servlet request

Spring manages different scopes (prototype, request, session, singleton). If two simultaneous requests access a singleton bean, then the bean must be stateless (or at least synchronized to avoid problems). If you access a bean in “request” scope, then a new instance will be generated per request. Spring manages this for you but you have to be careful and use the correct scope for your beans. Typically, your controller is a singleton.

About your last question “how this magic is happening?”, the answer is aspect/proxy. Spring creates proxy classes. You can imagine that Spring will create a proxy to your beans. As soon as you try to access it in the controller, Spring forwards the method call to the right instance.

Scope of a Spring-Controller and its instance-variables

https://stackoverflow.com/questions/11139571/scope-of-a-spring-controller-and-its-instance-variables

Are all controllers in Spring-MVC singletons and are shared among different sessions and requests? If so, I assume that a class-variable like public String name; would be the same for all requests and sessions?

Yes, Spring MVC controllers are singletons by default. An object field will be shared and visible for all requests and all sessions forever.

However without any synchronization you might run into all sorts of concurrency issues (race conditions, visibility). Thus your field should have volatile (and private, by the way) modifier to avoid visibility issues.

Tags

  1. Spring Beans
  2. Spring MVC - Accessing HttpRequest from controller