Archive for the ‘jsp’ Category

How to remove blank lines from the JSP output

August 24, 2007

A source of annoyance with the JSP output, where all the JSP directives are replaced with blank lines in the final output has been addressed in JSP 2.1. Now if you want to get rid of all the blank lines in your JSP output, simply add the line <%@page trimDirectiveWhitespaces="true"%> to the top of your JSP. I wish this was the default.

How to set the content type of a JSP

August 1, 2007

You can use a JSP to generate HTML or XML, … setting the content type of the JSP cannot be done in your servlet using request.setContentType() method, however. Instead, you must use the JSP content type directive. For example, to set the content type to text/xml, include the following line in your JSP.


<%@ page contentType=”text/xml” %>

How to pass a string or an object to a JSP

July 25, 2007

In your servlet pass the string that you wish to use in your JSP by setting the request or session attribute, i.e.,

request.setAttribute("foo", "Hello World!");

In your JSP (assuming that you’re using JSTL), simply reference foo (the name that you assigned to the string):

<c:out value="${foo}" />

If you want to pass an object, pass it in your servlet the same as above, but in your servlet, you need to declare it before you can use it:


<%@page errorPage="Error.jsp" %>
<%@ taglib prefix="c" uri="/WEB-INF/tld/c.tld" %>

<jsp:useBean id="foobar" class="com.mycompany.FooBar" scope="request">
	<jsp:setProperty name="foobar" property="*" />
</jsp:useBean>
...
<c:out value="${foobar.random}"/>

Your foobar class must be a bean, that is have getters & setters, e.g., foobar.getRandom()