Search code examples
javajspservletsstruts2struts-1

How to check if User Logged in or Not using Session Struts 2


I am working on struts2. I use below code to check if the User have logged in or not

public String execute()
{
   HttpServletRequest request = ServletActionContext.getRequest();
   HttpSession        session = request.getSession(false);

   System.out.println(session);

   if(session == null)
   {
      return "UserLoggedIn";    
   }

   return "success";
}

When I access print the session value in console first time it print null. But when I do the same thing by refreshing the page it prints some thing like below and its ends up letting the user to access the page with out logging in.

org.apache.catalina.session.StandardSessionFacade@16f21478

How to carry out session checking to see whether user logged in or not.

Thank you very much.


Solution

  • Well if you are just doing this for learning purpose, i believe its better to store a variable in session, once user logged in.

    Say, when use click login button and if credentials provided by user are correct you can store a variable (logged-in) in to session and on clicking log-out button can clear this variable.

    However there are few more things you need to take care.

    Its better to use SessionAware interface provided by Struts2 which is a clean way to inject Session as Map in you action class.

    public class YouAction implements SessionAware{
        private Map<String, Object> sessionMap;
          @Override
            public void setSession(Map<String, Object> sessionMap) {
                this.sessionMap = sessionMap;
            }
        }
    

    Above way let you action independent from direct dependencies from HTTP objects, which can be helpful in unit testing.

    If you have the option can use Spring security which is a much better way to handle User authentication and Authorization process.