I am new to spring and trying to develop a very basic application with database interaction.I want to know how to make user information available to all controllers and their methods as long as the user is logged in?? I am using spring mvc.
- use HttpSession to store user information when user logged in. This helps to understand what is session [link] stackoverflow.com/questions/3668153/what-is-session-in-javaDarshan Patel– Darshan Patel2014-01-01 09:52:26 +00:00Commented Jan 1, 2014 at 9:52
- Yes,i have done this using httpSession.setAttribute. Then in the required functions i have used httpSession.getAttribute,which is fetching me the desired output. However my problem is in these functions there is something like this @ModelAttribute("userDetails") UserFormbean userDetails to support the Jsp's. Now due to the presence of two form backing objects i am unable to edit,update the info. what should be done??Shivayan Mukherjee– Shivayan Mukherjee2014-01-01 10:17:31 +00:00Commented Jan 1, 2014 at 10:17
Add a comment |
1 Answer
Spring Security can help here. One the user logs in, you can access the user principal like this:
SecurityContext context = SecurityContextHolder.getContext(); Authentication auth = context.getAuthentication(); User user = (User) auth.getPrincipal(); 3 Comments
Shivayan Mukherjee
what will be the output for this??just the login id and pwd or all the details?
The user principal is arbitrary. By default I think
auth.getPrincipal() just returns a string (I don't recall for sure), but you can implement and register your own custom user service to return whatever kind of User object you like. It might have a username, first name, email, whatever you want.Here's a DZone RefCard I did on this: refcardz.dzone.com/refcardz/expression-based-authorization