Open In App

JSP | Declaration Tag

Declaration tag is one of the scripting elements in JSP.
This Tag is used for declare the variables. Along with this, Declaration Tag can also declare method and classes. Jsp initializer scans the code and find the declaration tag and initializes all the variables, methods, and classes. JSP container keeps this code outside of the service method (_JSPService()) to make them class level variables and methods. 

Syntax of JSP-Declaration Tag 






<%!  inside this tag we can initialise
our variables, methods and classes  %>

Example of JSP Declaration Tag which initialize a string




<%@ page language="java" contentType="text/html;
 charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
 
<body>
<!--declaration of username variable....  -->
<%! String username="Geeks"; %>
 
<!--In expression tag a string is initialised as Geeks -->
<%="Hello : "+username %>
 
<!-- Displaying expression using Expression Tag -->
</body>
</html>

Output: 



Example of JSP Declaration Tag which initializes a method 




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
<body>
 <html>
       <body>
        <%!
        int factorial(int n)
        {
        if (n == 0)
            return 1; 
          return n*factorial(n-1);
        }
          %>
         <%= "Factorial of 5 is:"+factorial(5) %>
        </body>
       </html>
</body>
</html>

Output 

Difference between the JSP Expression, Declarative, and Scriptlet tags 

 


Article Tags :
Uncategorized