You can use a Filter
for this which checks if the user is logged in by container managed security (i.e. HttpServletRequest#getUserPrincipal()
doesn't return null
) and then sets the session variable if not present.
Basically:
if (request.getUserPrincipal() != null && session.getAttribute("user") == null) {
session.setAttribute("userId", userId);
}
However, maybe you don't need to do it at all since it proves that you aren't aware about HttpServletRequest#getUserPrincipal()
. It may namely already offer exactly the information you need. The login username (it may be the same as the user ID where you're talking about) is available by Principal#getName()
.