Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ajax callback doesn't initiate the servlet variable?

 
Colin Zheng
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here I have JS code to call back the servlet:

...


Everytime when it sends the GET http request to the servlet, I wonder why it doesn't initiate the servlet variable "counter"? instead, the "counter" variable keeps increasing:



Doesn't the servlet 'new' itself everytime when there is a http request to it?

Thank you very much.

Colin
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64606
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Colin Zheng wrote:Doesn't the servlet 'new' itself everytime when there is a http request to it?

No.

And there is your answer (which has nothing at all to do with Ajax).
 
Colin Zheng
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the quick answer! Can you shed more lights on how the servlet initiates itself upon a http request? From another http client, the servlet definitely 'new' itself, right? I thought the http request is a stateless protocol.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64606
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that HTTP is stateless has nothing at all to do with the servlet life-cycle.

The container will load a servlet into memory before or on the first request to it. That single instance will be used to serve all requests to that servlet. This is why it is important to write servlets in a thread-safe manner. (Which yours is not, by the way.)

The servlet will be taken out of service by the container, usually when its context is being removed from service.

There are nuances to this, but that's the general life cycle of a servlet.
 
Colin Zheng
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you so much. Yes, I just proved that another client will affect the variable 'counter' so it's not thread safe. I have to learn more on how to make it thread safe. Moving on now...
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64606
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread-safe rule #1: no instance variables.
 
Colin Zheng
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But from the same client, I do want to track an event progress that is happening on the server side, large file uploading for example. I guess there is a lot more for me to learn.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic