Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

JSP Declaration Tag


The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet.

So it doesn’t get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

  1. <%!  field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare variables not methods. The jsp declaration tag can declare variables as well as methods.
The declaration of scriptlet tag is placed inside the _jspService() method. The declaration of jsp declaration tag is placed outside the _jspService() method.

Example of JSP declaration tag that declares field

In this example of JSP declaration tag, we are declaring the field and printing the value of the declared field using the jsp expression tag.

index.jsp

  1. <html>
  2. <body>
  3. <%! int data=50; %>
  4. <%= “Value of the variable is:”+data %>
  5. </body>
  6. </html>

Example of JSP declaration tag that declares method

In this example of JSP declaration tag, we are defining the method which returns the cube of given number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call the declared method.

index.jsp

  1. <html>
  2. <body>
  3. <%!
  4. int cube(int n){
  5. return n*n*n*;
  6. }
  7. %>
  8. <%= “Cube of 3 is:”+cube(3) %>
  9. </body>
  10. </html>

Comments

comments