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.

image with no caption

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.

image with no caption

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.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.