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
You don’t need to manage the sessions yourself. The servletcontainer will do it for you transparently in flavor of
HttpSession. You normally useHttpSession#setAttribute()to store an object in the session scope andHttpSession#getAttribute()to get an object from the session scope. You can useHttpServletRequest#getSession()to get hold of a reference to theHttpSession.E.g. in the login servlet:
You can get it back later in any servlet or filter in the same session by
You can even access it by EL in JSP:
(assuming that there’s a Javabean
getUsername()method)