apache commons lang3 stringutils taglib
Asked Answered
R

3

5

Id like to use StringUtils.abbreviate() inside a jstl tag, is there a taglib location for this?

Ive searched the commons site and the web but an unable to find an example. Is there a common way to find taglib locations also, maybe in a standard location of a javadoc tree??

Thanks! Nic

Rounder answered 26/12, 2012 at 14:8 Comment(0)
T
4

Nic,

There often isn't a predefined tag to get at the apache util methods, but it's easy to add your own special tag definitions to point to the method you want. For example, add a local taglib definition to your web.xml file:

<jsp-config> 
    <taglib> 
        <taglib-uri>mytags</taglib-uri> 
        <taglib-location>/WEB-INF/jsp/mytaglib.tld</taglib-location> 
    </taglib> 
</jsp-config>

Your mytaglib.tld file will look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <tlib-version>1.0</tlib-version>
    <function>
        <description>Exposes the abbreviate() function from Apache StringUtils</description>
        <name>abbreviate</name>
        <function-class>org.apache.commons.lang.StringUtils</function-class>
        <function-signature>java.lang.String abbreviate(java.lang.String,
                            int)</function-signature>
    </function>
</taglib>

In your JSP, you can then use your new custom tag:

<%@ taglib prefix="mytags" uri="mytags" %>
...
<c:out value="${mytags:abbreviate(myString, 5)"/>

That should do it for you. For more info on custom tags, you can read here: http://docs.oracle.com/javaee/5/tutorial/doc/bnalj.html

Templeton answered 26/12, 2012 at 22:28 Comment(0)
C
2

I wrote one for commons-lang 2.4.

https://github.com/hussachai/commons-lang-taglibs

You can use it as a template for 3.0 by the way.

Charge answered 10/4, 2013 at 23:22 Comment(0)
C
2

I was initially thinking of going with a custom taglib also. Thanks for the post, it gave me this idea. Creating an instance of StringUtils worked just fine on it's own. Even though the calls are static. I suppose you could wrap it into a two-liner tag if you wanted to.

The example below will output the following: Now is the t...

<%@ tag import="org.apache.commons.lang3.StringUtils" %>
<jsp:useBean id="StringUtils" class="org.apache.commons.lang3.StringUtils" />
<c:out value="${StringUtils.abbreviate('Now is the time for all good', 8) }" />

Note that the tag import statement seems to be optional. The above code works for me with or without it.

Chromosphere answered 13/7, 2018 at 14:25 Comment(1)
It even works inside Jelly scripts without importing, if using "org.apache.commons.lang.StringUtils". Thanks!Squad

© 2022 - 2024 — McMap. All rights reserved.