There’s a better way: use the <c:out> tag

Whichever approach you use, it’s a bit unclear exactly what’s going on... and you may have to write that helper method for all your servlets. Luckily, there’s a better way. The <c:out> tag is perfect for the job. Here’s how conversion works:

You can explicitly declare the conversion of XML entities

If you know or think you might run into some XML entities that need to be displayed, and not just rendered, you can use the escapeXml attribute on c:out. Setting this to true means that any XML will be converted to something the web browser will render, angle brackets and all:

image with no caption

You can explicitly declare NO conversion of XML entities

Sometimes, you want just the opposite behavior. Maybe you’re building a page that takes content, and you want to display that content with HTML formatting. In that case, you can turn off XML conversion:

image with no caption

Conversion happens by default

The escapeXml attribute defaults to true, so you can leave it out if you want. A c:out tag without an escapeXml attribute is just the same as a c:out tag with escapeXml set to “true.”

image with no caption

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.