Strip whitespace from jsp output

There is a trimWhiteSpaces directive that should accomplish this,

In your JSP:

<%@ page trimDirectiveWhitespaces="true" %>

Or in the jsp-config section your web.xml (Note that this works starting from servlet specification 2.5.):

<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <trim-directive-whitespaces>true</trim-directive-whitespaces>
  </jsp-property-group>
</jsp-config>

Unfortunately if you have a required space it might also need strip that, so you may need a non-breaking space in some locations.


If your servletcontainer doesn't support the JSP 2.1 trimDirectiveWhitespaces property, then you need to consult its JspServlet documentation for any initialization parameters. In for example Tomcat, you can configure it as well by setting trimSpaces init-param to true in for JspServlet in Tomcat's /conf/web.xml:

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

A completely different alternative is the JTidyFilter. It not only trims whitespace, but it also formats HTML in a correct indentation.


Not directly what you're asking for, but what helps me is putting HTML comment tags in a clever way around my jsp tags, and also putting whitespace inside a servlet tag (<% %>):

${"<!--"}
<c:if test="${first}">
    <c:set var="extraClass" value="${extraClass} firstRadio"/>
</c:if>
<c:set var="first" value="${false}"/>
${"-->"}<%

%><input type="radio" id="input1" name="dayChooser" value="Tuesday"/><%
%><label for="input1" class="${extraClass}">Tuesday</label>

If you're using tags, you can apply there too:

<%@ tag description="My Tag" trimDirectiveWhitespaces="true" %>

And on your jsp:

<%@ page trimDirectiveWhitespaces="true" %>