JSP Declaration tag is a block of java code used for declaring class wide variables and methods. The code placed inside declaration tag 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 %>
Difference between JSP Scriptlet tag and Declaration tag
JSP Scriptlet Tag | JSP Declaration Tag |
---|---|
The JSP scriptlet tag can only be used to declare variables, it cannot declare methods. | The JSP declaration tag can be used to declare variables as well as methods. |
The declaration of scriptlet tag is placed inside the _jspService() method. The variables declared inside _jspService() are local so these variables are not available class wide. |
The declaration of jsp declaration tag is placed outside the _jspService() method. The variables and methods declared by JSP declaration tag are available at class level. |
Example 1: Variables declaration using JSP Declaration tag
In this example we have declared two variables inside declaration tag and displayed them on result page using expression tag. The variables declared are name
and age
, where name
is a string type variable and age
is an integer variable. We accessed the value of these variables on the JSP page 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 using JSP Declaration tag
In this example we have declared a method sum using JSP declaration tag. This method accepts three integer parameters and returns the sum of these numbers. Here, we are passing three numbers 10, 40 and 50 to the method sum()
declared using JSP declaration tag. The method returns the sum of these numbers which is 100 as displayed on the output screenshot.
<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.
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…….