views:

3785

answers:

4

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?

+10  A: 

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.

Rontologist
That is interesting, thanks for the answer.
James McMahon
Unfortunately this does not work in Tomcat 6.0.24
Kdeveloper
+1  A: 

Any performance implications of using this directive? Does it slow down the generating output?

That depends on servlet container you use. Most of them use it as a compiler hint, and it only affects the compile time.
Rontologist
+1  A: 

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

http://raibledesigns.com/rd/entry/trim_spaces_in_your_jsp1

Simon B
+2  A: 

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.

BalusC
I have configured by setting trimSpaces init-param to true in /conf/web.xml but the spaces in the generated html are not trimmed.I am using Tomcat 6.0. Any ideas?
ria
@ria: Note that you need to understand that this only trims whitespace left by taglibs like JSTL and scriptlets. If you want to trim ALL whitespace from HTML, then head for a different solution. You can find a filter example here: http://balusc.blogspot.com/2007/12/whitespacefilter.html
BalusC
Thank you BalusC..
ria