Middle+
What do you know about creating custom JSP tags?
sobes.tech AI
Answer from AI
Custom JSP tags allow creating your own elements that encapsulate repetitive display logic or server-side behavior. This improves code readability and reusability in JSP.
The typical steps to create a custom tag are:
- Creating a tag class — a class that implements the
Taginterface or extendsSimpleTagSupport, where the tag logic is described. - Defining a TLD file (Tag Library Descriptor) — an XML file that describes the tags, their attributes, and the associated class.
- Including the tag library in JSP — using the
<%@ taglib %>directive to include the TLD.
Example of a simple custom tag that outputs a greeting:
public class HelloTag extends SimpleTagSupport {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public void doTag() throws JspException, IOException {
getJspContext().getOut().write("Hello, " + name + "!");
}
}
TLD file (hello.tld):
<tag>
<name>hello</name>
<tag-class>com.example.HelloTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
</tag>
In JSP, including and using the tag:
<%@ taglib prefix="ex" uri="/WEB-INF/hello.tld" %>
<ex:hello name="World" />
Thus, custom tags allow creating convenient and reusable components for JSP.