Step 13- JSP Tags

Tag TypeSyntaxPurpose
Scriplet tags<% code %>Used to embed Java code directly into a JSP page. The code within a scriplet tag is executed every time the JSP page is requested.
Expression tags<%= expression %>Used to include the result of an expression in a JSP page. The expression within an expression tag is evaluated and the result is included in the output.
Declaration tags<%! code %>Used to declare class-level variables and methods in a JSP page. The code within a declaration tag is inserted into the _jspService() method of the generated servlet.
Directive tags<%@ directive %>Used to provide information to the JSP container, such as importing classes or setting the content type. Directive tags begin with <%@ and are typically used to set page-level properties.
Taglib Directive<%@taglib prefix=”tagname” uri=”taglib uri” %>Used to include the custom tag in JSP page.
Custom tagscustom tag elementUsed to encapsulate complex logic in a JSP page. They are created using the JSP tag extension API.

1- Scriplet tag:

<html>
<body>
<% 
int x = 5;
int y = 10;
int result = x + y;
%>
<h2>The result of <%= x %> + <%= y %> is <%= result %></h2>
</body>
</html>

2- Expression tag:

<html>
<body>
<% 
int x = 5;
int y = 10;
int result = x + y;
%>
<h2>The result is <%= result %></h2>
</body>
</html>

3- Declaration tag:

<html>
<body>
<%! 
int calculateSum(int a, int b) {
    return a + b;
}
%>
<%
int x = 5;
int y = 10;
int result = calculateSum(x, y);
%>
<h2>The result of <%= x %> + <%= y %> is <%= result %></h2>
</body>
</html>

4- Directive tag:

<%@ page import="java.util.Date" %>
<html>
<body>
<h2>Current date and time: <%= new Date() %></h2>
</body>
</html>

5- Taglib Directive:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:forEach var="i" begin="1" end="5">
   <c:out value="${i}"/>
</c:forEach>
</body>
</html>

6- Custom Tag :

<%@ taglib prefix="mytag" uri="taglib uri" %>
<html>
<body>
<mytag:greetings name="John"/>
</body>
</html>