Monday, July 23, 2012

Placing your custom tags inside a JAR with Maven

I recently wrote an article about packaging a TLD file inside a JAR and how to reference it to enable systematic reuse for these resources.
Other resources that likely you want to reuse are your custom tags.
This is very similar to packaging TLDs function files.
Let's start with a simple tag that substitutes the well-known IE checks for the CSS.
So, instead of writing
<!--[if IE 8]>
<link rel="stylesheet" href="ie.css" type="text/css" />
<![endif]-->
we'll be able to write
<my:ie test="IE 8" css="ie.css" />

The tag itself is quite easy. It will look like that
<jsp:root xmlns:c="http://java.sun.com/jsp/jstl/core"
 xmlns:fn="http://java.sun.com/jsp/jstl/functions"
 xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
 <jsp:output omit-xml-declaration="yes" />

 <jsp:directive.attribute name="check" required="true" />
 <jsp:directive.attribute name="css" required="false"/>
 
 <jsp:text><![CDATA[<!--[if ${check}]>]]></jsp:text>
 <c:if test="${not empty css}">
  <link rel="stylesheet" href="${css}" type="text/css" />
 </c:if>
 <jsp:doBody />
 <jsp:text><![CDATA[<![endif]-->]]></jsp:text>

</jsp:root>

Actually this tag does also something more, but that's out of the scope of this article.
Now all you need to do is to place this tag inside the src/resources/META-INF directory. If you want to be tidy, you can even place it under a subdirectory, "tags" for example.
Now all you need to do is to add a TLD file under the META-INF directory as explained in the aforementioned articles describing your new tag, like that:
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2eeweb-jsptaglibrary_2_0.xsd" version="2.0">
 <tlib-version>1.0</tlib-version>
 <uri>http://mynamespace.org/tags/</uri>
 
 <tag-file>
  <name>ie</name>
  <path>/META-INF/tags/ie.tagx</path>
 </tag-file>
 
</taglib>
Be careful to use the correct value for the URI tag because that's the trick to reference this file from your JSP projects.

Hope you can find this helpful,
Stefano

2 comments:

  1. Nice blog!
    So based on your example, I understand that the header in my JSP should be something like:

    < html xmlns:my="http://mynamespace.org/tags/">
    ....


    ReplyDelete
    Replies
    1. Correct, Micheal.
      Never tried to place the namespace declation inside the HTML node, but it works with DIV so I don't see why it shouldn't work with HTML.

      Delete