4

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.

ksbg
  • 3,214
  • 1
  • 22
  • 35

4 Answers4

6

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

Artur
  • 334
  • 5
  • 15
Harsh Poddar
  • 2,394
  • 18
  • 17
  • Thank you very much for this simple answer, I am new at hibernate, and to be good in it I was creating an e-commerce web app with maven using hibernate and looking for it for the last 8-9 hour, I came across many explanations and video but this is a simplest and exact line I was looking for. Thank yo very much. –  Apr 14 '21 at 05:36
2

HttpSession is different from the Hibernate session. The Hibernate session provides a way for you to query and save persistent entities that are stored in a database. The HttpSession is provided by the servlet container to give a way to store objects for a given user based on a cookie provided in the user's request.

What you store in the HttpSession should be minimal, partly to save on overhead from nodes in the cluster reconciling their sessions but mostly to make your application less error-prone. Here it could be sufficient to store a user's ID in the session rather than the whole user object. Even if the User object contained roles it would be better to look those up for each request so that any changes get applied immediately. Also by storing only ids you avoid problems with reattaching entities (allowing you to avoid one of the more confusing and troublesome parts of using Hibernate). When something else in your application needs to access the User it can query the Hibernate session (using session.get(id)) passing in the primary key value stored in the HttpSession.

You should use a 1-way hash to store passwords so that will change how you compare passwords.

The application should create a Hibernate SessionFactory once only upon initialization, it is threadsafe and everything in the application should use that one instance.

Rolling back a transaction where all you do is select seems unnecessary.

Typically you access the HttpSession only from the view and the web controller. It looks like you have web controller logic and business logic lumped together, a division of responsibilities between controller and service may be helpful here.

Community
  • 1
  • 1
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
1

The Session you have mentioned here(org.hibernate.Session) is cannot access from the other places of your web site instead you put your User object into a HttpSession .

Here is how you going do this:

HttpSession httpSession = request.getSession();
httpSession.setAttribute("loggedUser", your_user_object reference_here );

Here is how you access from other placess:

httpSession.getAttribute("loggedUser");//return type is Object here
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36
1

Assuming you are in a Web application and you want something from the User entity, you should propagate the same value/reference to the Web/controller layer (in case you are using an MVC approach); then keep it there since it's the most appropriate place to store something via the HTTP session provided by most frameworks.

RECOMMENDATION(S)

  • You should not be rolling back a get/select operation?
  • A SessionFactory should be instantiated once.
x80486
  • 6,627
  • 5
  • 52
  • 111