简体   繁体   中英

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!!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM