ADS

Jsp Declaration Tag Example

In this example you are going to learn about the JSP declaration tag. This tag is used to declare member variables and methods of the servlet class corresponding to our JSP file.

Let me explain this more clearly. When we write a JSP file, the JSP container (jasper.jar) automatically writes a corresponding servlet (.java) file, compiles it and deploys it.

Now with the help of the JSP declaration tag we can declare variables and methods that were members of that servlet class. Don't believe me? Well, I'll show you the proof below. Let us move to the example first.

Folder structure:
webapps
            |_ jsp2
                    |_ index.jsp

Syntax

<%!
// declaration of variables and methods of the servlet class
%>

Note the exclamatory mark (!). If you forget it, it will be a scriptlet tag.

Example - index.jsp

 <%!
int a=10;
    public int getA()
    {
    return a;
    }
%>
<%
    out.println("The value of a is "+getA());
%>

Here a is a member variable of the servlet class corresponding to the JSP file and getA() is the member method that returns the value of a. Now, in the scriptlet (i.e.) in the _jspService() method we are calling the getA() and we are printing it. So the output will be:

 
The value of a is 10

index_jsp.java - Corresponding servlet

You can find this file in 

C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\jsp1\org\apache\jsp

Here is a sample structure of the file (need not be exactly the same, i'm telling the outline):

public simpulan class index_jsp
{
int a=10;
         public int getA()
         {
         return a;
         }

         public void _jspService(HttpServletRequest req,HttpServletResponse res)
         {
         out.println("The value of a is "+getA());
         }
}

Subscribe to receive free email updates:

ADS