• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between %! and % when declaring variables in .jsp

 
Vedek Bareil
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone tell me what is the difference in the examples below ?


--------


Yeah, I know the first example is using scriplet-tags and the second declaration-tags, but what's the difference or is there any ?

Is there any reasons why should one not declare variables in scriplet-tags ?

Thanks.
 
arnel nicolas
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


...means that the compiler must run to this code first before executing the rest of the code. The above declaration is useful for initializing constants and variables in your page.Other than it will just be an ordinary JSP script.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65530
108
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not quite.

Code declared using 'declaration' notation is placed at class level within the generated servlet class. Scriplets become code in the service() method.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

declares a static int foo.
Translates into the servlet as



declares an instance variable foo.
Translates into
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No... a declaration doesn't make it "static", just a regular attribute. You *can* declare static attributes/methods/etc. but you would have to explicitly declare them as static... it's not something implicit in the JSP declaration. Declaring a variable in a scriptlet tag defines it inside the _jspService() method, making it a local variable. Here's a look at the code that might be created by each tag -



 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65530
108
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nathan is correct; declarations are not automatically made static.

The best thing you can do for yourself (besides avoiding scriplets in JSPs completely), is to find the Java file that the servlet container creates on behalf of your JSP. Anytime you don't understand something, or your JSP is acting strange, looking at this file can usually clear things right up. Tomcat stores these files in a hierarchy under $CATALINA_HOME/work.

For example, take the following simple JSP:



Tomcat 5 turns this into:



Looking at the translated servlet classes in this way has saved me dozens of hours of hair-pulling (ummm, no hair, so beard-pulling perhaps?)
[ July 15, 2004: Message edited by: Bear Bibeault ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!