Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feed rendered jsp pages through htmltidy

I have a Java project running on Glassfish that renders some ugly looking HTML. Its a side effect from using various internal and external JSP libraries. I would like to set up some sort of post-render filter that would feed the final HTML through HTMLTidy so that the source is nice and neat to aid debugging. Is this possible?

Is there a built in mechanism to perform some action after the server renders the JSPs into HTML? Can that action get the generated HTML as a string and manipulate it? Is there some easy built-in option to do this without extra coding?

like image 361
Freiheit Avatar asked Feb 02 '10 18:02

Freiheit


2 Answers

JTidyFilter

like image 136
axtavt Avatar answered Nov 14 '22 03:11

axtavt


This behaviour can also be eliminated to a certain degree by setting the JSP 2.1 property trimDirectiveWhitespaces to true. This can be enabled in individual JSP files by:

<%@page trimDirectiveWhitespaces="true" %>

Or on all JSP files by the following entry in web.xml (which needs to be declared Servlet 2.5!):

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

In pre-JSP 2.1 containers or in JSP 2.1 containers which actually doesn't support this for some internal reasons, such as Tomcat, you need to consult its JspServlet documentation for any initialization parameters. In for example Tomcat, you can configure it as well by setting the trimSpaces init-param of JspServlet to true in Tomcat's /conf/web.xml:

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

Noted should be that the both approaches doesn't really "reformat" the HTML code. It actually only trims the whitespace which is left by taglibs and scriptlets. Also see this Sun article. So for example the following..

<ul>
    <c:forEach items="${list}" var="item">
        <li>${item}</li>
    </c:forEach>
</ul>

..would basically end up in

<ul>
        <li>item1</li>
        <li>item2</li>
        <li>item3</li>
</ul>

Thus with double indentation. You can actually workaround this by reformatting the code as such that JSP tags are half-indented:

<ul>
  <c:forEach items="${list}" var="item">
    <li>${item}</li>
  </c:forEach>
</ul>

But I think the JTidyFilter is easier here :)

like image 31
BalusC Avatar answered Nov 14 '22 02:11

BalusC