We need another JSP element...
Declaring the count variable in a scriptlet meant that the variable was reinitialized each time the service method ran. Which means it was reset to 0 with each request. We need to somehow make count an instance variable.

So far we’ve looked at directives, scriptlets, and expressions. Directives are for special instructions to the Container, scriptlets are just plain old Java that lands as-is within the generated servlet’s service method, and the result of an expression always becomes the argument to a print() method.
But there’s another JSP element called a declaration.

JSP declarations are for declaring members of the generated servlet class. That means both variables and methods! In other words, anything between the <%! and %> tag is added to the class outside the service method. That means you can declare both static variables and methods.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access