This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
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.
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