Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

What's servlet?

  Asked By: Caleb    Date: Aug 13    Category: Java    Views: 674

I declared a servlet class with doGet()
inside:class CounterServlet int intCount;
doGet(){intCount++;}}Variable intCount is not static, but it
acts like static,
why?Is it true that every servlet has it's one doGet
method, but other pieces of code like class-level
variables and methods are shared between all clients?



1 Answer Found

Answer #1    Answered By: Gerald Cruz     Answered On: Aug 13

Only one instance of the servlet  is created in
the JVM. However, each time you call the doGet or
doPost method on a servlet, a new thread of that method
is created.Therefore, the class  variable
inCount only is created once, but each time you call the
doGet/doPost (and any other person who calls it through a
browser) will increment the single instance of
intCount.You need to keep your doPost/doGet methods
threadsafe. Unless you want the above behavior (a counter for
people visiting the page or something like that), you
need to make all your variables method level
scope.What you want the servlet to do each time you call it,
should be contained in the doGet/doPost method anyway.
Access variables declared in those methods.

Didn't find what you were looking for? Find more on What's servlet? Or get search suggestion and latest updates.