Why does this PrettyTime custom tag produce 11 lines of blank text before the “pretty” date in the HTML output?

点点圈 提交于 2019-12-11 20:57:00

问题


<%@ 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:


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)}" />



回答2:


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



来源:https://stackoverflow.com/questions/4018741/why-does-this-prettytime-custom-tag-produce-11-lines-of-blank-text-before-the-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!