SetLocale did not work in jsp site to format curre

2020-07-09 07:31发布

问题:

I'm confused with the jstl tag libs:

I want to format a number to a currency with german style ... but everything I tried did not worked ...

I found the following example but the output is the same -.-

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
      prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"
      prefix="fmt" %>

<html>
<head>
    <title>format number</title>
</head>
<body>
    <c:set var="val" value="40.52" />
    <p> Currency in USA
    <fmt:setLocale value="en_US"/>
    <fmt:formatNumber value="${val}"
              type="currency" />
    </p>

    <p>Currency in Germany
    <fmt:setLocale value="de_DE"/>
    <fmt:formatNumber value="${val}"
              type="currency"/>
    </p>
</body>
</html>

And thats the output:

Currency in USA $40.52

Currency in Germany $40.52

what goes wrong there ?

thanks for your help.

回答1:

Awesome, by chance I got the solution to my problem:

The trick is to set the scope-parameter of the setLocale tag to session :D and then it works ^^ sweet :)

So the correct code snippet looks like:

<c:set var="val" value="40.52" />
<p> Currency in USA
<fmt:setLocale value="en_US" scope="session"/>
<fmt:formatNumber value="${val}"
          type="currency" />
</p>

<p>Currency in Germany
<fmt:setLocale value="de_DE" scope="session"/>
<fmt:formatNumber value="${val}"
          type="currency"/>

Ok, I do not really know why it works, but here is some more information about my project setup:

  • Spring 3 Framework (MVC, Security usw.)
  • and a standard application and servlet Setup
  • every thing runs in tomcat 7 so I use JSP 2.2

Hope it helps.



回答2:

I had the same problem. But i think it has to do with property files. I had 2 property files, text.properties and text_sv.properties, and when the initial locale was any other than 'sv' i could change it with fmt:setLocale anywhere in my jsp-files. But when the initial locale was 'sv', fmt:setLocale did nothing. Session doen't work..