tags:

views:

26

answers:

3

I just switched over to Tomcat 6.0.26 from a different Servlet/JSP engine. Previously, null values would print out as an empty String. However, Tomcat is printing out nulls as "null".

<% String str = null; %>
The value of str is <%= str %>.

This outputs

The value of str is null.

How can I get Tomcat to replace nulls with empty/blank strings?

A: 

By replacing null with "". That should do what you want.

Dean
+1  A: 

Looks like you want to fix this in your code as there doesn't appear to be an option in tomcat to turn this behaviour off. (There apparently is in weblogic if that's what you were using - see "printNulls").

From the javadocs of Tomcat's JspWriterImpl#print()

public void print(java.lang.String s)
throws java.io.IOException

Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

Specified by:
print in class javax.servlet.jsp.JspWriter
Parameters:
s - The String to be printed
Throws:
java.io.IOException - If an error occured while writing

jskaggz
Thanks for fixing my formatting BalusC :-)
jskaggz
+2  A: 

This is default and expected behaviour. Apparently the previous server has some proprietary configuration setting for that. None in Tomcat comes to mind.

Regardless, scriptlets is a vintage technique and its use is discouraged over a decade. It has been succeeded by taglibs (like JSTL) and Expression Language (EL) in combination with a Servlet as controller.

E.g. in Servlet's doGet():

String str = null;
request.setAttribute("str", str);
request.getRequestDispatcher("page.jsp").forward(request, response);

and in page.jsp:

The value of str is ${str}

EL will by default print nothing if the value equals null while scriptlet expression (<%= %>) by default prints whatever String#valueOf() returns.

See also:

BalusC