Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Servlet instance

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a two questions in regards to a servlet.
I have built a small web app, that basically uses a servlet. This servlet loops and during each loop displays a new web page. My first problem seems to be that when I run the servlet its instance does not seem to die once I exit the site and when I re-enter the application evfen from another computer I am in the same place that I was in the previous run of the application, on the previous machine.
My second problem basically is relatyed to the first. When I instanciate the servlet once, all the connections are using the same instance instead of creating there own new ones.
If anyone could help I would reallyu appreciate it.
thank you very much.
Karen Lin
 
Karthik Guru
Ranch Hand
Posts: 1209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
make ur servlet implement SingleThreadModel interface and
see what happens. There are no methods to be implemented. It's just a flag like Cloneable / serializable. I hope then the server w'd start churning different instances for each request.
karthik.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
SingleThreadModel will help with neither problem, unfortunately. It will work around the thread-unsafeness of the servlets, but since a session will not "stick" to a single servlet, it will still make a mish-mash of the site.
Karen, you are trying to use servlets in a way in which they are not intended to be used. Servlets are interchangeable, and not associated with a single client session. Their lifetime is managed by the server and completely independent from any one user. They cannot and should not keep any information (instance variables) about a user's conversation with the system.
Of course you still need to keep such conversational state - in your case, something indicating the "current page" - somewhere. That is where the HTTP session object (javax.servlet.http.HttpSession) kicks in. You can retrieve it from the request object. Each user has its own HttpSession.
What your servlet should do is retrieve the HttpSession from the request, get the current page (session.getAttribute("currentPage") or something similar), advance it to the next page, store the new value back in the session, and show the page. That way, a single servlet can handle multiple users without confusion because all the state is not in the servlet, but in the users' session objects.
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic