Sanjay
Sanjay

Reputation: 11

Save a database value in a session

I am quite new in java and servlets. I would like to know how to store a value retrieved from a database in a session variable so that i can use it for comparison and on other pages. Any help will be greatly appreciated.

Thank you!!

Upvotes: 1

Views: 1805

Answers (1)

BalusC
BalusC

Reputation: 1108722

Just use HttpSession#setAttribute() to store an object in the session along with a known attribute name.

SomeObject someObject = someDAO.find(someId);
request.getSession().setAttribute("someObject", someObject);

In subsequent requests in the same session, you can re-obtain it by HttpSession#getAttribute() using the attribtue name.

SomeObject someObject = (SomeObject) request.getSession().getAttribute("someObject");
// ...

It's even accessible in JSP files by EL

${someObject}

which is useful if it's a fullworthy Javabean.

Upvotes: 3

Related Questions