At some point in your use of JSP, there’s something you’re going to need to do for which you can’t find a spring or jstl tag. In that case, you can create a custom function in your custom tag library. It sounds more difficult than it is. All you will need is a tag library descriptor, and your class that implements the function. That’s about it. Here’s my TLD file.
<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/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>2.0</tlib-version> <uri>http://www.your-domain.com/taglib</uri> <function> <name>doMyStuff</name> <function-class>com.mydomain.util.ElFunctions</function-class> <function-signature>java.lang.String doMyStuff( java.util.Collection )</function-signature> </function> </taglib>
This file should be placed in your WEB-INF directory. In the function-signature, be sure to use fully qualified names.
Next is the class that implements the function.
package com.mydomain.util.ElFunctions; import java.util.Collection; /** * Functions for use in expression language in the jsp views. */ public class ElFunctions { /** * This is the function that is called by the Expression Language processor. It must be static. * @param myparam * @return */ public static String doMyStuff( Collection<SomeType> myparam ) { // do stuff here and return the results } }
Finally, just reference the function in my jsp file.
<%-- where you declare your taglibs, include this one, which references the tld we created in the first step. --%> <%@ taglib prefix="my" uri="/WEB-INF/my.tld" %> <!-- more html and whatever, in my case I'm using spring:message to output the results of my method call --> <spring:message text="${my:doMyStuff(bean.collection)}" />
The call to ${my:doMytuff(bean.collection)} causes the EL processor to call my function when it evaluates that snippet. In this case, ‘bean’ would be some java bean available to the view, and ‘collection’ would be a property on the bean that returns the collection expected as input to doMyStuff.