VOOZH about

URL: https://www.geeksforgeeks.org/java/jsp-declaration-tag/

⇱ JSP | Declaration Tag - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JSP | Declaration Tag

Last Updated : 14 May, 2026

The Declaration Tag in JSP is used to declare variables, methods, and classes in a JSP page. The code written inside this tag is placed outside the _jspService() method by the JSP container, making it available throughout the JSP page.

  • Uses <%! %> syntax to declare variables, methods, and classes
  • Declarations become class-level members of the generated servlet
  • Used for defining reusable logic, not for direct output

Syntax:

<%! declaration code %>

Example: JSP Declaration Tag which initializes a string

Output: 

👁 Geeks
output

Explanation:

  • <%! String username = "Geeks"; %> → Declares a class-level variable named username
  • This variable is stored outside _jspService(), so it is accessible throughout the JSP
  • <%= "Hello: " + username %> → Uses Expression Tag to display the value on browser

Example : JSP Declaration Tag which initializes a method 

Output

👁 Factorial
Output

Explanation:

  • <%! int factorial(int n) { ... } %> -> Declares a method inside JSP
  • The method is part of the generated servlet class and can be reused
  • return n * factorial(n - 1) -> Uses recursion to calculate factorial
  • <%= factorial(5) %> -> Calls the method and prints result using Expression Tag
Comment
Article Tags:
Article Tags: