Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting HttpSession from the init method

 
igwe kalu kalu ogba
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I know that the normal way to get the httpsession is by using:

HttpSession session = request.getSession(true);
String dbName = (String) session.getAttribute("dbName");

inside a doGet or doPost method.

However is it possible to get the session object from the servlet's init method. I know init looks like this : init().
Can I override it? maybe init (HttpServlet request) or something?
If not how else can I get the session in a servlet.
My servlet is using init because it loads on startup . Many thanks.
 
Ola Daniel
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Igwe, When a servlet loads at startup, that means an instance of the servlet is started as soon as the web app is deployed. No session can exist at this stage.

Can someone please confirm that.

Can you use the Application Context for whatever you are considering setting in session instead?

eg...


This response is based on the assumption that yu want to instatiate a session to store objects.
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A session is used to identify clients across requests. At startup there is no request, so Ola is correct in pointing out that there can be no session. That's also the reason why you get a session through Request, and not ServletContext.
[ August 26, 2005: Message edited by: Ulf Dittmer ]
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to pre-load each session with certain information when it's created, you could use an HttpSessionListener
If this information is always going to be the same for all session, then it would make more sense, as Ola suggested, to store this information in context scope instead.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic