Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store retrieved object in session and access it afterwords?

I am trying to create a simple login page. I retrieve a User object from my database using hibernate. That part works fine, I'm doing that as follows:

//data from login form
String username = request.getParameter("username").trim();
String password = request.getParameter("password").trim();

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
    User currentUser = (User) session.get(User.class, username);
    if(password.equals(currentUser.getPassword())) {
        response.sendRedirect("index.jsp?page=login&success=true");
    } else {
        session.getTransaction().rollback();
        response.sendRedirect("index.jsp?page=login&success=false");
    }
} catch //...

Given the correct credentials, login is successful. If I understand correctly, my code above already stores the User in the session, if the login was successful, so all I have to do is access the session?

However I can't figure out how to access the retrieved User object from the session in other places of my website. After the user is logged in, I want to show user-specific information on my website and for that, I need to check the username and whether the user is logged in at all.

So to sum up: How can I use the retrieved User object in other parts of my website?

I just started learning Java EE and hibernate, so please bear with me.

like image 498
ksbg Avatar asked Nov 02 '15 16:11

ksbg


1 Answers

You can do it using an HttpSession that can be retrieved by the HttpServletRequest object.

HttpSession httpSession = request.getSession();
httpSession.setAttribute("user", user);

Now to check if the user object is present in different parts of your application, you can do the following:

HttpSession httpSession = request.getSession(false); 
//False because we do not want it to create a new session if it does not exist.
User user = null;
if(httpSession != null){
    user = (User) httpSession.getAttribute("user");
}

if(user!=null){
    // Do stuff here
}

To logout a user or in other words, to invalidate the session, you can call the invalidate method.

httpSession.invalidate();

Useful links: HttpServletRequest and HttpSession

like image 181
Harsh Poddar Avatar answered Oct 09 '22 06:10

Harsh Poddar