How can I strip out extra whitespace from jsp pages' output? Is there a switch I can flip on my web.xml? Is there a Tomcat specific setting?
There is a trimWhiteSpaces directive that should accomplish this,
In your JSP:
<%@ page trimDirectiveWhitespaces="true" %>
Or in the jsp-config section your web.xml
<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.
Any performance implications of using this directive? Does it slow down the generating output?
This should really be a comment to the first answer, I don't think I have sufficient points to make a comment. So if someone can copy this an put it in as a comment for that answer it would be great.
The trimDirectiveWhitespaces is only supported by servlet containers that support JSP 2.1 and after, or in the case or Tomcat, Tomcat 6 (and some versions e.g. Tomcat 6.0.10 don't implement it properly - don't know about the others), there's more information about trimDirectiveWhitespaces here:
http://java.sun.com/developer/technicalArticles/J2EE/jsp_21/
and here
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.