File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Servlet instance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlet instance" Watch "Servlet instance" New topic

Servlet instance

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Mar 06, 2001
Posts: 1209
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.
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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
I agree. Here's the link:
subject: Servlet instance
It's not a secret anymore!