JSP Declaration Tag

JSP declaration tag is used to declare variables and methods in JSP page. Unlike scriptlet tag, JSP container placed the content of declaration tag outside the jspService() method. So, variables and methods declared in declaration tag are static or instance.

The syntax of declaration tag is as follows:

<%! variable and method declaration %>

The variable and method inside declaration tag is up to the class level. We can put any number of variables and methods inside declarative tag.

Example of declaring variables in JSP Declaration Tag

Along with declaring variable, this example also shows that declaration tag doesn't get memory at each request.

index.jsp

<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h1><center>
<%!
String name="Tutorial and Example";
int count=0;
%>
<%out.print("Website name:"+name);
out.print("<br>Number of time access:"+ ++count);
%>
</center></h1>
</body>
</html>
Output:

Example of declaring methods in JSP Declaration Tag

In this example, a method is declared inside declaration tag and has been accessing from scriptlet tag.

Index.jsp

<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<center>
<h1>JSP Declarative Method Example </h1>
<h2>
<%!
int marks(int english,int math,int science)
{
    return english+math+science;
}
%>
<%out.print("Total marks = "+marks(72,75,80));%>
</h2>
</center>
</body>
</html>
Output: