What is the value in using the "<%!" scriptlet tag versus the "<%" when declaring constants?

Serge Knystautas

Constants and fields declared in the "<%!" scriptlet tag have a different scope than those declared in "<%". Those in <%! are defined at the servlet class level (the servlet that is autogenerated by the JSP engine), while those in <% are defined in the service method. If you use fields defined in <%!, they are only created when the servlet is initialized. Also, they are shared, so if your servlet is handling multiple requests simultaneously, that field is getting used concurrently. If you use fields defined in <%, they are created each time a request is handled, and are unique to that request.

If you need share a field across multiple requests, use <%!. If you have a constant that never changes, also use <%! as then it is only defined once. For all other uses, you'll want to use <%, otherwise you'll likely encounter some strange concurrency issues.