John Rumpel
John Rumpel

Reputation: 4615

JSTL Formatting: Confusing IllegalargumentException

I have an object formatobject in session scope, with a member of type SimpleDateFormat sdf based on a pattern "dd.MM.yyyy HH:mm:ss".

I want to use the JSTL formatting tag library to format my output:

<fmt:formatDate value="${dataobject.date}" pattern="${formatobject.sdf}"/>

This gives me the following exception:

org.apache.jasper.JasperException: java.lang.IllegalArgumentException: Illegal pattern character 'j'

When I try the following, it works as expected:

<fmt:formatDate value="${dataobject.date} pattern="dd.MM.yyyy HH:mm:ss"/>

Confusing ... do you have an idea?

Upvotes: 0

Views: 510

Answers (1)

BalusC
BalusC

Reputation: 1109222

The pattern attribute has to refer a String representing the pattern, not a concrete SimpleDateFormat instance constructed around the pattern.


Unrelated to the concrete problem, SimpleDateFormat is not threadsafe, yet your attempt implies that it's been created in constructor of formatobject and reused session/application wide. This is not right. The SimpleDateFormat must be declared and created on a thread local basis (i.e. inside the method block). The pattern is the only part which can be a constant.

So, all with all, this is right:

public class Formatter {

    private static final String PATTERN = "dd.MM.yyyy HH:mm:ss";

    public String format(Date date) { // Just an example. No idea how you're further using it.
        return new SimpleDateFormat(PATTERN).format(date); // Always create SimpleDateFormat in method local scope. Never create it as instance variable.
    }

    public String getPattern() {
        return PATTERN;
    }

}

with

<fmt:formatDate ... pattern="#{formatter.pattern}" />

Upvotes: 2

Related Questions