What are the main types of tags in JSP?
sobes.tech AI
Answer from AI
JSP uses three main types of tags:
-
Scriptlets: Allow you to insert Java code directly into an HTML page. Used for business logic execution or data access.
// Java code insertion <% String user = "Guest"; System.out.println("Hello, " + user); %> -
Declarations: Used to declare variables and methods at the JSP level. These declarations are accessible from any scriptlet on the page.
// Declaration of a variable or method <%! private int counter = 0; public String getMessage() { return "This is a declaration."; } %> -
Expressions: Used to output the value of variables or expression results to the page. The result is converted to a string and inserted into HTML.
// Output the value of a variable or expression <%= new java.util.Date() // Output current date %>
In addition to the main types, there are also:
-
Directives: Control the behavior of the JSP container during the translation of the JSP page into a servlet. For example,
page,include,taglib.<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -
Action Tags: Predefined XML elements that perform standard tasks such as including other resources or creating JavaBean objects. Examples include
jsp:include,jsp:forward,jsp:useBean.<jsp:include page="header.jsp" /> -
Custom Tags: Allow developers to define their own tags for reusing functionality and improving JSP readability. Used with the
taglibdirective.<%-- Example of using a custom tag --%> <%@ taglib prefix="my" uri="/WEB-INF/mytld" %> <my:hello name="World"/>