Declaration Tag
We know that at the end a JSP page is translated into Servlet class. So when we declare a variable or method in JSP inside Declaration Tag, it means the declaration is made inside the Servlet class but outside the service(or any other) method. You can declare static member, instance variable and methods inside Declaration Tag. Syntax of Declaration Tag :
<%! declaration %>
Example of Declaration Tag
<html> <head> <title>My First JSP Page</title> </head> <%! int count = 0; %> <body> Page Count is: <% out.println(++count); %> </body> </html>
In the above code, we have used the declaration tag to declare variable
count
. The above JSP page becomes this Servlet :public class hello_jsp extends HttpServlet { int count=0; public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { PrintWriter out = response.getWriter(); response.setContenType("text/html"); out.write("<html><body>"); out.write("Page count is:"); out.print(++count); out.write("</body></html>"); } }
In the above servlet, we can see that variable
count
is declared outside the _jspservice()
method. If we declare the same variable using scriptlet tag, it will come inside the service method, as seen in the last lesson.When to use Declaration tag and not scriptlet tag
If you want to include any method in your JSP file, then you must use the declaration tag, because during translation phase of JSP, methods and variables inside the declaration tag, becomes instance methods and instance variables and are also assigned default values.
For example :
<html> <head> <title>My First JSP Page</title> </head> <%! int count = 0; int getCount() { System.out.println( "In getCount() method" ); return count; } %> <body> Page Count is: <% out.println(getCount()); %> </body> </html>
Above code will be translated into following servlet :
public class hello_jsp extends HttpServlet { int count = 0; int getCount() { System.out.println( "In getCount() method" ); return count; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { PrintWriter out = response.getWriter(); response.setContenType("text/html"); out.write("<html><body>"); out.write("Page count is:"); out.print(getCount()); out.write("</body></html>"); } }
While, anything we add in scriptlet tag, goes inside the
_jspservice()
method, therefore we cannot add any function inside the scriptlet tag, as on compilation it will try to create a function getCount()
inside the service method, and in Java, method inside a method is not allowed.