• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Instance varaible in JSP scriplet

 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.




 
Ranch Hand
Posts: 874
Android VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Balu for your excellent explaination!!!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic