How would I write (just a template) for a custom tag with 2 attributes that lets me output a html fragment (a html table) using jstl tag logic, that can be called from my jsp.
Can this be done without writing a java class, which is what I have seen in all the examples.
What I'm trying to acheive is to externalise repeated JSTL logic in my JSPs into a custom tag then pass the dynamic values needed to the tag at run time using the attributes.
Thanks,
A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on a tag handler. The web container then invokes those operations when the JSP page's servlet is executed. Custom tags have a rich set of features. They can.
For creating any custom tag, we need to follow following steps: Create the Tag handler class and perform action at the start or at the end of the tag. Create the Tag Library Descriptor (TLD) file and define tags. Create the JSP file that uses the Custom tag defined in the TLD file.
A custom tag library is a set of custom tags that invoke custom actions in a JavaServer Pages (JSP) file. Tag libraries move the functionality provided by the tags into tag implementation classes, reducing the task of embedding excessive amounts of Java™ code in JSP pages.
Don't use scriptlets! They're a bad practice and they let business-logic leak into your view layer.
You can create a tag file using JSTL; it's pretty simple. This is a good place to start.
An example:
mytable.tag:
<%@ attribute name="cell1" required="true" type="java.lang.String" description="Text to use in the first cell." %>
<%@ attribute name="cell2" required="false" type="java.lang.String" description="Text to use in the second cell." %>
<table>
<tr>
<td id = "cell1">${cell1}</td>
<td id = "cell2">${cell2}</td>
</tr>
</table>
Assuming that your tag is in /WEB-INF/tags
, you can then use it like this:
<%@ taglib prefix="mystuff" tagdir="/WEB-INF/tags" %>
<mystuff:mytable cell1="hello" cell2="world" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With