Java.Servlet.What are the main types of JSP tags?

📜 1. Directive Tags

  • Used to give instructions to the JSP engine at translation time (before the page is turned into a servlet).
  • They control things like page settings, imports, and file inclusion.

Syntax:

<%@ directive attribute="value" %>

Examples:

  • <%@ page language="java" contentType="text/html" %> → Page settings
  • <%@ include file="header.jsp" %> → Static include
  • <%@ taglib uri="..." prefix="..." %> → Use custom tag libraries (JSTL, etc.)

📜 2. Scripting Tags

  • Allow you to embed Java code directly inside the JSP page.
  • (Not recommended for large applications — better to use JSTL or EL.)

Types of scripting tags:

Types of scripting tags:

TypeSyntaxPurpose
Declarations<%! Java code %>Declare variables or methods
Scriptlets<% Java code %>Write Java code blocks
Expressions<%= Java expression %>Output a Java value directly

Example:

<%! int counter = 0; %>          <!-- Declaration -->
<% counter++; %>                 <!-- Scriptlet -->
<p>Counter: <%= counter %></p>   <!-- Expression -->

📜 3. Action Tags

  • Special tags that interact with JavaBeans, forward requests, include content, and reuse components.
  • Handled by the JSP engine.

Syntax:

<jsp:actionName attribute="value" />

Examples:

  • <jsp:useBean> → Create or find a JavaBean
  • <jsp:setProperty> → Set bean property
  • <jsp:getProperty> → Get bean property
  • <jsp:include> → Include another resource at runtime
  • <jsp:forward> → Forward the request to another page

📜 4. Standard Tag Libraries (JSTL)

  • A set of ready-to-use tags for common tasks like:
    • Conditions (<c:if>)
    • Loops (<c:forEach>)
    • Formatting
    • SQL database access
  • Removes the need to write Java code inside JSP pages.
  • Cleaner, easier, safer!

Example using JSTL:

<c:if test="${user != null}">
    <p>Welcome, ${user.name}!</p>
</c:if>

Here ${user.name} is evaluated using EL (Expression Language).

📜 5. Custom Tags

  • You can define your own tags with special behavior.
  • Usually used in large projects to avoid repetitive code.
  • Created using:
    • Java classes implementing SimpleTagSupport or TagSupport
    • Defined in a .tld (Tag Library Descriptor) file or via annotations.

Example of usage:

<mytags:showDate />

where mytags is a custom tag library you define.

🎯 Final Summary:

Tag TypeMain Use
Directive TagsGive instructions to the JSP container
Scripting TagsEmbed Java code inside HTML
Action TagsWork with JavaBeans, include, forward
Standard Tag Libraries (JSTL)Common operations like loops, conditions
Custom TagsDefine reusable custom behavior
This entry was posted in Без рубрики. Bookmark the permalink.