I have a Spring 5 based webapp where the controller calls this service class and gets the current logged in User information.
Since loggedInUser object has been defined as an instance variable here, will this create a race condition when multiple users try to log into the application and access pages with their credentials ?
Should this be a local variable instead of instance variable within the getLoggedInUser() method ?
I was under the impression that Tomcat will create a new thread for every HTTP request and a brand new instance of UserService bean will be created every time a request comes in, irrespective of the user accessing it.
And how can I identify if the bean used by Spring is new instance or singleton? Is there a way to check this at runtime using System.out.println() or any other methodology/tool?
So,
User 1 -> new UserController() -> new UserService() -> welcome.jsp
User 1 -> new ProductController() -> new ProductService() -> new UserService() -> product.jsp
User 2 -> new UserController() -> new UserService() -> welcome.jsp
User 2 -> new ProductController() -> new ProductService() -> new UserService() -> product.jsp
UserService.java
@Service
public class UserService {
private User loggedInUser;
public User getLoggedInUser(HttpServletRequest request) {
if (this.loggedInUser != null) {
return this.loggedInUser;
}
this.loggedInUser = (User) session.getAttribute("loggedInUser");
return loggedInUser;
}
}