JSTL custom tag

van picture van · Jul 29, 2011 · Viewed 11.2k times · Source

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,

Answer

Vivin Paliath picture Vivin Paliath · Aug 23, 2011

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" />