A JSP quirk

In JavaServer Pages, expressions are escaped by “<%=” and “%>”. For example, <%= 1 + 1 %> would output 2.

On the Tomcat web server, JSP gets translated into a servlet. The above expression declaration is implemented as a translation into the following line of Java code embedded in a Servlet:

out.print( 1 + 1 );

According to the JSP specification, a translation error will occur if the expression inside the declaration is not well formed in the underlying language (i.e., is not a valid Java expression).

A fun quirk of JSP on the Tomcat server is that the following code doesn’t result in a compile error:

<%= ""); out.print("Hello, World!" %>

Obviously, ""); out.print("Hello, World!" is not a valid Java expression. However, Tomcat uses a superficial syntactic translation. Here’s what the above declaration looks like after translation:

out.print( ""); out.print("Hello, World!" );

This is valid Java, despite not being translated from a valid Java expression.

You shouldn’t and wouldn’t want to rely on this behavior. Instead, it is just a fun quirk that I like to use when teaching how JSP works under the hood.

Continue Reading (Published 19 November 2017)

Published 1 January 2017 by Benjamin Johnston.