Tuesday, 14 April 2009

JSP Substring (and other string manipulations)

I only have a little knowledge of jsp, so my first stab at trying to modify a page I thought I'd try just using some Java to see happened.

The modification was just to substring a variable that already existed, so in went the Java and out came the error.

The function substring must be used with a prefix when a default namespace is not specified

What? So I did some searches for this error and eventually found that using Java was very wide of the mark.

You need to use the jstl tag library for string manipulation.

So after adding the taglib to the top of the page, my substring that trims the first five characters and the last character looks something like:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="myValue" value="${fn:substring(myValue,5,fn:length(myValue)-1)}" />

A summary of all the functions in the jstl library, including: contains, endsWith, escapeXml, indexOf, join, length, replace, split, trim, can be found at JSTL functions.


No comments: