Declaration tag is a block of java code for declaring class wide variables, methods and classes. Whatever placed inside these tags gets initialized during JSP initialization phase and has class scope. JSP container keeps this code outside of the service method (_jspService()) to make them class level variables and methods.
As we know that variables can be initialized using scriptlet too but those declaration being placed inside _jspService() method which doesn’t make them class wide declarations. On the other side, declaration tag can be used for defining class level variables, methods and classes.
Syntax of declaration tag:
<%! Declaration %>
Example 1: Variables declaration
In this example we have declared two variables inside declaration tag and displayed them on client using expression tag.
<html> <head> <title>Declaration tag Example1</title> </head> <body> <%! String name="Chaitanya"; %> <%! int age=27; %> <%= "Name is: "+ name %><br> <%= "AGE: "+ age %> </body> </html>
Output:
Example 2: Methods declaration
In this example we have declared a method sum using JSP declaration tag.
<html> <head> <title>Methods Declaration</title> </head> <body> <%! int sum(int num1, int num2, int num3){ return num1+num2+num3; } %> <%= "Result is: " + sum(10,40,50) %> </body> </html>
Output:
Sum of all three integers gets displayed on the browser.
Let us know if you have any questions.
mahesh agga says
Hiii Sir your tutorials are very easy to understand… and please upload the webservices tutorials as sooon as possible
manjunath k says
hep me related to structure concepts in jsp…….