kovike
kovike

Reputation: 551

How to make fmt:setLocale work on fmt:formatNumber with only language code in JSP?

I'm trying to localize currency on my JSP web application, problem is when I ask for locale, I only get language code ("en") instead of full language and country code ("en_US"). Problem with this is, formatNumber doesnt work when setLocale's value doesn't contain language and country code.

I can solve it by checking for locale language at the beginning of the jsp page and setting default country code for few languages and then setting value of setLocale, but this method looks pretty ugly to me. Is there a better way of doing this?

This is how I do it now:

<c:choose>
    <c:when test="${pageContext.response.locale == 'cs'}">
        <f:setLocale value="cs_CZ" />
    </c:when>
    <c:otherwise>
        <f:setLocale value="en_US" />
    </c:otherwise>
</c:choose>
<f:formatNumber type="currency" value="${product.price}" currencyCode="CZK"/>

Upvotes: 3

Views: 8196

Answers (2)

Pointy
Pointy

Reputation: 413866

You're using Stripes!! Stripes will handle the locale for you, and you should be getting it from the ActionBeanContext:

<c:set var='curLocale' value='${actionBean.context.locale}'/>

Don't go around Stripes' back! That is the path to distress and unhapiness! Stripes is your friend!

In general, you should not need to use <fmt:setLocale> because Stripes already sets up the locale in the Stripes filter. Again, Stripes is your friend!! Read about this in the Stripes wiki:

http://www.stripesframework.org/display/stripes/Localization

Upvotes: 4

BalusC
BalusC

Reputation: 1109302

The currency is dependent on the country, not on the language. You really need to set it as well. A more generic way is to use a Filter for this so that you don't need to copypaste the check in every JSP.

Update: I now see that you're using HttpServletResponse#getLocale() which returns the programmatically set locale or otherwise the container's default locale. The normal practice is to use HttpServletRequest#getLocale() to get the client's locale, thus so:

${pageContext.request.locale}

See if that helps. You however still need to check if the country is actually present. A Filter is the best place for that.

Upvotes: 4

Related Questions