JSP Declaration tag

A declaration tag is used to declare one or more variables or methods at the class level. Variables and methods declared in the declaration tag are initialized at the time of JSP initialization. These variables and methods are kept outside of the service method by the web container to make them class-level.

Syntax:

 <%!  Variable or method Declaration %>

Example:

welcome.jsp

<html>
    <head>
        <title>Declaration tag example</title>
    </head>
    <body>
        <%!
            int sum(int a, int b){
            return a + b;
        }
        %>
 
        <%
            out.println("Sum of 10 and 20 = " + sum(10, 20));
        %>
    </body>
</html>

web.xml

<web-app>
 
  <welcome-file-list>
          <welcome-file>welcome.jsp</welcome-file>
  </welcome-file-list>	
 
</web-app>