Processing incomparable strings in JSP date formatting

I am writing a JSP that sometimes needs to format the Java date that comes out of the request. I do it like this:

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

and it works great on Java Dates.

However, there are times when a request attribute field with the same name ( attribute.value) is not really a date and should not be formatted as such. What I would like to do is simply pass this line through the fmt:formatas-is tag , and not throw an exception on the failed validation date.

I could do something similar with c:choose, but I would rather separate the JSP presentation from the underlying data as much as possible, so this is not an ideal choice for me. So, is there a way to do something like

<fmt:formatDate value="I AM NOT A DATE" pattern="yyyy-MM-dd HH:mm:ss"/>

just appreciate

I AM NOT A DATE

in generated HTML?

+3
2

:

<c:catch var="ex">
    <fmt:formatDate value="${attribute.value}" pattern="yyyy-MM-dd HH:mm:ss"/>
</c:catch>
<c:if test="${not empty ex}">
    ${attribute.value}
</c:if>

, , .

+3

:-) , c: , JSP - , , , :

<your:formatDate value="I AM NOT A DATE" pattern="yyyy-MM-dd HH:mm:ss"/>

(, , .)

, .

EDIT: , - :

1) "WEB-INF/tags/someNamespace/yourTag.tag" :

<%@ tag isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ attribute name="date" type="java.util.Date" required="true" %>
<c:choose>
<c:when test="${date instanceOf java.util.Date}">
<fmt:formatDate value="${date}" pattern="yyyy-MM-dd HH:mm:ss"/>
</c:when>
<c:otherwise>${date}</c:otherwise>
</c:choose>

2) :

<%@ taglib tagdir="/WEB-INF/tags/someNamespace" prefix="s" %>

3) :

<s:yourTag date="${attribute.date}"/>

, , , .

+3

Source: https://habr.com/ru/post/1716342/


All Articles