Basic Operational Question on Tomcat/Servlets
OK; so I'm new to the whole servlet/java/webapps thing, but I'm steadily learning. I just have a quick question on the basic operation of how they work. Let me explain my setup.
I have a Google Chrome extension that takes some input from the user, and then forwards that input (using an xmlhttprequest) on to a tomcat server which has a servlet on it. That servlet processes the request and then sends back a response.
My question is this: Is a new instantiation of the java servlet created every time I make the request to the server, or is one instance persisting for the life of the server? My servlet will give predictions based on past history, so it's rather important that it can remember things from the past.
Thanks so much for your help.
Re: Basic Operational Question on Tomcat/Servlets
In the lifecycle of a webapp container and according to the servlet spec the container (Tomcat) should only ever create one instance of each servlet class, therefore the class itself is not threadsafe per such as you should not have class member variables that you write to from the doGet/doPost methods.
You can think of it as two requests can come in to the servlet at the same time, however because of the way Java works even though both requests hit the same servlet instance they will be in two different threads so therefore two different method stacks will be created when the doGet/doPost methods are called. However if you now try to write to a servlet class member from that method both request threads will potentially overwrite each others values as they use the same object.
To solve your issue with give response based on previous answers etc you can use the session object. See HttpSession (Servlet API Documentation)
The session is something that tomcat magically takes care of for you so you don't need to worry about that, all you need to do is grab the session off the request object and then you can store values in it such as previous answers etc. and the next time that session makes another request you can grab those values from the session and base your new answers from that.
Hope this makes some sense.