Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Instance varaible in JSP scriplet  RSS feed

 
Jay Shukla
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Head First JSP K & B (page No: 294), it is mentioned that

"Declaring the count variable in the a scriplet means that the variable was reinitialized every time the service method ran. Which means it wa reset to 0 with each request.We need to somehow make count an instance variable."


In above statement count varaible was initially local variable so it was reinitialize to 0 with each request, now they are tryinh to make that variable an instance variable.

Can anyone let me explain what is the difference between instance variable and local variable in above context or hoe an instance variable will solve it, because every object has its own copy of instance variable.


Thanks in Advance.




 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Jay,

As you are aware the JSP ( including servlets) are intialised only once in their lifecycle ( which means only one instance) and this intialisation occurs for the first request ( if its not precompiled) hence form the next request only _jspservice() method is called . If you could see the compiled code its better to understand.

So any variable declared inside the _jspservice is local variables , which are intialised for every request. Hence to declare instance variable , it has to be declared outside _jspservice() method and is done inside <%! tag.

So each time the page is requested , the "same single instance variable " count is used.

By the way , in real world applications instance variables are to avoided ( I would say not really needed ) becauses its not thread safe.
 
Jay Shukla
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Balu for your excellent explaination!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!