0

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.

Shivayan Mukherjee
  • 766
  • 3
  • 10
  • 33
  • use HttpSession to store user information when user logged in. This helps to understand what is session [link] http://stackoverflow.com/questions/3668153/what-is-session-in-java – Darshan Patel Jan 01 '14 at 09: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 Jan 01 '14 at 10:17

1 Answers1

0

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();
  • what will be the output for this??just the login id and pwd or all the details? – Shivayan Mukherjee Jan 01 '14 at 10:07
  • 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. –  Jan 01 '14 at 10:24
  • Here's a DZone RefCard I did on this: http://refcardz.dzone.com/refcardz/expression-based-authorization –  Jan 01 '14 at 10:24