views:

19

answers:

2
<%@ tag language="java" pageEncoding="utf-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ tag import="com.ocpsoft.pretty.time.PrettyTime, java.util.Date"%>
<%@ attribute name="dateParam" required="true" type="java.util.Date" %>

<%
 PrettyTime p = new PrettyTime();
 String prettyDate = p.format(dateParam);
 jspContext.setAttribute("prettyDate", prettyDate.trim());
%>
<c:out value="${prettyDate}"/>

I can't figure out if I'm doing something wrong in this tag.

The PrettyTime library is supposed to just print a text version of a data, e.g.:

10 months ago

But I can't tell why this custom tag produces 11 lines of blank text before the "pretty" date in the HTML output?

+1  A: 

Because when you remove the <%...%>'s there are still newlines left which faithfully are reproduced in the generated output.

Thorbjørn Ravn Andersen
+1  A: 

Since Thorbjoern has already answered the cause, I'll only answer the solution since you'd likely to get rid of this annoyance.

You can configure your servletcontainer to trim whitespace left after processing the scriptlets and taglibs. In for example Apache Tomcat, you can do it by opening the /conf/web.xml, heading to the <servlet> definition of the JSP servlet, which look like follows on Tomcat 7

<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>

add an <init-param> of trimSpaces=true as follows to the <servlet> definition of JSP servlet:

    <init-param>
        <param-name>trimSpaces</param-name>
        <param-value>true</param-value>
    </init-param>

Restart Tomcat and this whitespace should be gone. At least, most of will be gone. You only need to take care that the whitespace which you've introduced yourself is physically removed from the JSP as well.

See also the JSP engine HOW-TO. Pretty all other servletcontainers have a similar configuration. Consult their documentation using the keyword "trim spaces".


As to the general approach, I'd suggest to transform that thing into a Java class and make an EL function of it instead. Death to the scriptlets.

<c:out value="${my:prettyTime(date)}" />
BalusC