• Post Reply Bookmark Topic Watch Topic
  • New Topic

Wether Declaration is used to create Static variables or instance variables

 
Amirtharaj Chinnaraj
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Fokes

i have created a JSP like as below



And got the output as below
The value of b multiplied by a is 300

what my question is line <%! int b = 30; %>
decleared a instance variable b.But without an instance of this servlet this variable b
is acessed in this line The value of b multiplied by a is <%= b * a %>

so instance variable should be accessed with an instance. ie SERVLETOBJ.b.if i declare <%! static int b = 30; %>
i should not have ask this question

looking for your replies
thanks
Amir
 
Shankar Tanikella
Ranch Hand
Posts: 329
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
firstly sorry that you are using scripting.

However, whatever (variables/methods) you declare in the JSP are actually declared in the JSP's Servlet class and hence it need not be explicitly mentioning the scope of the instance.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65519
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scriptlets have been discredited for over 9 years now. Why are you still using them in your JSPs?

Scriptlet declarations end up at class level in the generated servlet class, while scriptlet blocks end up inside the service() method.
 
Stefan Evans
Bartender
Posts: 1822
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


That is an approximation of what your JSP will produce in servlet code.
No, you should not have had to ask this question.

Your understanding of the servlet life-cycle should have told you that the container will instantiate this class, and invoke the "service()" method.
the "b" referenced from the service method is effectively "this.b".

EDIT: Just adding one more tidbit. According to the servlet spec, only one instance of the Servlet is created to handle all the requests (unless you use the horrible isThreadSafe declaration). So in some ways it IS similar to having a static variable. But it is not actually static.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!