Define JSP Declaration with example
A JSP declaration is enclosed within <%! %>. This tag allows you to declare variables and methods that can be used elsewhere in the JSP file. These declarations are placed outside of the _jspService method, meaning they are part of the JSP page’s servlet class but not part of the main request processing logic.

Table of Contents
Here’s a simple example of using a JSP to define a method and a variable:
Example
jsp
<%@ page language="java" %>
<%!
// Declaration of an instance variable
private int counter = 0;
// Declaration of a method
public int getNextCounterValue() {
return ++counter;
}
%>
<html>
<head>
<title>JSP Declaration Example</title>
</head>
<body>
<h1>Counter Value: <%= getNextCounterValue() %></h1>
</body>
</html>
Explanation of the JSP
1. Â Variable Declaration :
- Â Â Â jsp private int counter = 0;
- Â Â Â This line declares a private integer variable counter and initializes it to 0.
2. Â Method Declaration :
- jsp
- public int getNextCounterValue() {
- Â Â Â Â Â Â Â return ++counter; }
- – This method increments the counter variable and returns its new value.
3. Â Using the Method in JSP :
- jsp
- Â <h1>Counter Value: <%= getNextCounterValue() %></h1>
- Â The method getNextCounterValue() is called within an expression tag <%= %>, which outputs the result to the client.