Scripting Elements


The scripting elements provide us the ability to insert the java code inside our jsp page.

There are 3 types of scripting elements:

  1. scriptlet tag
  2. expression tag
  3. declaration tag

1. JSP Scriplet Tag

The scriplet tag is used to execute the java source code in our jsp page.

The Jsp scriptlet tag can declare only the variables, not the methods.

This tag is declared inside the _jspService() method.

Syntax:

    <% Java code %>


Example: In the following example, we have created 2 files index.html and greet.jsp. The index.html file will take the name from user and greet.jsp file will greet the user with his name.

index.html

    <form action=”greet.jsp” >
        <input type=”text” name=”uname” />
        <input type=”submit” value=”Submit name” />
    </form>


greet.jsp

    <html>
        <body>
            <% String name = request.getParameter(“uname”);
            out.println(“Hi “ + name); %>
        </body>
    </html>



2. JSP Declaration Tag

The declaration tag is used to declare static members, instance variables and methods.

The jsp declaration tag can declare both variables and methods.

This tag is declared outside the _jspService() method.

Syntax:

    <%! Declaration code %>


Example:

    <html>
        <head>
            <title>Tutorialsduniya JSP tutorial</title>
        </head>
        <body>
            <%! int square(int n){
            return n*n;
            } %>
            Square is : <% square(7) %>
        </body>
    </html>


3. JSP Expression Tag

The expression tag is used to print the java expression placed between these tags. So we don’t need out.print() to print the data.

Syntax:

    <%= expression statement %>


Example: In the following example, we are greeting the users of TutorialsDuniya.com.

    <html>
        <body>
            <%= “Welcome to TutorialsDuniya.com” %>
        </body>
    </html>