Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting User Name from Within HttpSessionListener

Tags:

java

servlets

I would like to get the username from within HttpSessionListener.sessionCreated(). When I say username, I mean specifically that name that is returned by HttpServletRequest.getRemoteUser().

Obviously, there must have been a HttpServletRequest object that caused the session to be created (and hence the sessionCreated() call). But how do I access it from within sessionCreated()? The HttpSessionEvent object passed into sessionCreated() appears to provide no way to get at the HttpServletRequest object that caused the session to be created.

like image 400
John Fitzpatrick Avatar asked May 12 '26 05:05

John Fitzpatrick


1 Answers

The HttpSessionListener does not have access to the HttpServletRequest object because it is invoked when no request has been made—to notify of session destruction or creation.

So, a Filter would be better places where you can add username = request.getRemoteUsr() into session.

Example - Filter Code

String username = request.getRemoteUsr() ;
session.setAttribute("username",username);

and then retrive this username in sessionCreated method as

String username = (String)session.getAttribute("username");

i hope you will get the same username of the same request which has created this session in HttpSessionListener sessionCreated() method.

like image 58
Rahul Agrawal Avatar answered May 13 '26 19:05

Rahul Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!