Saturday, July 24, 2010

New Line Output in JSP

The Problem :
JSP Output contains unnecessary line feeds within generated HTML. While this is normally cosmetic I had an issue last week where a the JSP file was generating a CSV file. The CSV file was then used to import data elsewhere and the empty lines were being interpreted as the EOF.

Example JSP
<!-- START EXAMPLE -->
<c:set var="testVariable" value="Hello World" />
<h1><c:out value="${testVariable}" /></h1>

HTML output
<!-- START EXAMPLE -->

<h1>Hello World</h1>


The Solution
A quick although not very elegant solution to the problem is to add newline characters within the JSP tags. Below is a simple JSP page that uses this method
<!-- START EXAMPLE -->
<c:set var="testVariable" value="Hello World" 
/> <h1><c:out value="${testVariable}" /></h1>

HTML output
<!-- START EXAMPLE -->
<h1>Hello World</h1>