Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design question - Persistent data in a webapp session

Tags:

java

jsp

servlets

I am developing a web app using servlets and jsps. I have a question about storing data I need to use across multiple servlets in a login session. When the user logs in, for example, I get the user object from the db and would like to store it somewhere and have the subsequent servlets and jsps use it without having to query the db again. I know that I have to store the object in a global array but am not able to figure out the best way to do this.

I am thinking of having a static hashmap or some other data structure created at webapp load time and I can use that to store the user object with the sessionID as the key for the hashmap.

Is there a better way? Any help is appreciated.

Thanks, - Vas

like image 657
user220201 Avatar asked May 17 '26 09:05

user220201


2 Answers

You don't need to manage the sessions yourself. The servletcontainer will do it for you transparently in flavor of HttpSession. You normally use HttpSession#setAttribute() to store an object in the session scope and HttpSession#getAttribute() to get an object from the session scope. You can use HttpServletRequest#getSession() to get hold of a reference to the HttpSession.

E.g. in the login servlet:

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user);
} else {
    // Show error?
}

You can get it back later in any servlet or filter in the same session by

User user = (User) request.getSession().getAttribute("user");
if (user != null) {
    // User is logged in.
} else {
    // User is not logged in!
}

You can even access it by EL in JSP:

<p>Welcome, ${user.username}!

(assuming that there's a Javabean getUsername() method)

like image 180
BalusC Avatar answered May 19 '26 23:05

BalusC


There is a way to do this and it's defined in the servlet spec. You can get hold of the HttpSession object and add objects as "attributes".

Take a peek at the API here: http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpSession.html

like image 32
Tom Duckering Avatar answered May 19 '26 22:05

Tom Duckering



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!