Scripting Elements in JSP

The scriptlet tag is used to write the Java code inside the JSP page. JSP scripting elements are written inside <% %> tags.

JSP Scripting Elements

There are three types of scripting elements:
  • scriptlet tag
  • declaration tag
  • expression tag

JSP scriptlet tag

JSP scriptlet tag is used to write Java code inside JSP page. It executes source code.

Syntax:
<% java code %>

Example : implements JSP scriptlet tag

<html>
<head>
     <title>
          My First JSP Page
     </title>
</head>
<body>  
     <% out.print("Welcome to JSP world"); %>  
</body>  
</html>


Output:
                     Welcome to JSP world

JSP Declaration Tag

  • JSP declaration tags are used to declare variable fields and methods.
  • The declaration tag is placed outside the service method and inside the Servlet class to make them class level variable and methods.
Syntax:
<%!  Declaration %>

Example : Declaring a method inside Declaration Tag

<html>
    <head>
         <title>JSP Declaration Tag</title>
    </head>
<body>
    <%! int square(int a)
    {
        return a * a;
    }
    %>
    <% = "Square of 5 is: "+square(5) %>
</body>
</html>


Output:
Square of 5 is: 25

JSP Expression Tag

  • JSP expression tag is used to write the client response to the output stream.
  • Expression tag keeps the expression that can be used as an argument to the output stream method.
Syntax:
<%= Java Expression %>

Example : Displays current date using Expression tag

<%@page contentType="text/html" import="java.util.*" %>
<html>
     <head>
         <title>JSP Expression Tag</title>
     </head>
<body>
     <h2>Current Date</h2>
     <p>
          Today's Date: <%= (new java.util.Date()).toLocalString() %>
     </p>
</body>
</html>


Output:
Today’s Date: 03-Aug-2016 10:52:21

JSP Comments

  • JSP comment is text or statement that is not considered by JSP container.
  • JSP comments are hidden in JSP page source and ignored by JSP container.
Syntax:
<%-- JSP comment --%>

Example : JSP comment tag

<html>
    <head>
        <title>JSP Comments</title>
    </head>
<body>
    <%--   this will hide on JSP page --%>
</body>
</html>