Search code examples
javajspstruts

How to Format a Value within a JSP?


I'm working on a J2EE application which uses Struts (v1) and I would like to format a value being displayed in a JSP. The value to be displayed is a 7 or 8 digit integer and I would like to insert dashes into it, like so:

1234567 -> 1-234-567
12345678 -> 12-345-678

What is the best way to go about this? My first thought was to write a special getter in my form bean which would return the specially formatted String, rather than the Integer. That, of course, seems very smelly - I don't want to add methods to my beans just to format things in my JSP.

Another option I considered was to use bean:write's format attribute. Unfortunately, I can find lots of documentation on how to use format when you're trying to format a date, but I just can't seem to find the correct syntax for working with arbitrary values.

Any thoughts?


Solution

  • I did some researching on fmt:formatNumber... I think using - is causing some weird problem because , is the only safe grouping separator. Based on the documentation, it seems like you can comment special character using single quotes, but I don't think it applies in your case.

    So, here's my workaround:-

    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    
    <c:set var="foo" value="12345678"/>
    <fmt:formatNumber value="${foo}" pattern="00,00,000" var="result"/>
    ${fn:replace(result, ",", "-")}
    

    This works for me. Basically, I use commas instead of dashes, then use the replace function to convert it back to dashes... not quite an elegant solution.