views:

1387

answers:

4

Hi,

Is there any way to convert a string to Title case, using JSTL tags?

Thanks in Advance.

+3  A: 

An idea:

In a class, create a simple method that uses the WordUtils from Apache Commons Lang that will manipulate your String:

import org.apache.commons.lang.WordUtils;

...

public static String titleCase(String input){
   return WordUtils.capitalize(input);;
}

And now, create your own tag (in a function.tld) :

<?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/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
  <description>functions library</description>
  <display-name>functions</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>xfn</short-name>
  <uri>http://yourdomain/functions.tld&lt;/uri&gt;
  <function>
    <description>
      Title case a String
    </description>
    <name>titleCase</name>
    <function-class>Functions</function-class>
    <function-signature>java.lang.String titleCase(java.lang.String)</function-signature>
    <example>
      ${xfn:titleCase(string)}
    </example>
  </function>
</taglib>

ps: I was quite inspired from this post to give my answer.

romaintaz
He's looking for Title Case not all uppercase
Eric Labashosky
The capitalize() method does not transform your String in uppercase ! Eventually do StringUtils.capitalize(StringUtils.lowerCase(theString)) !
romaintaz
+3  A: 

An alternative to transforming the string on the server is to let CSS do the work:

text-transform: capitalize
McDowell
cool. It helped, since I needed the Title Case only for presentation purpose, CSS would be a better solution. Thanks.
Why always looking for complex answer? Your solution is really the best one!
romaintaz
+2  A: 

jstl supports that using a function

${fn:toUpperCase(textVar)}

http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fn/tld-summary.html

Edit: I just realized Title Case is something else than uppercase! That makes this anwser completely wrong, sorry!

Simon Groenewolt
A: 

It's not too super hard in JSTL...

${fn:toUpperCase(fn:substring(user.firstName, 0, 1))}${fn:toLowerCase(fn:substring(user.firstName, 1, -1))}

jonnad