Preprocessing JSP files to automatically escape EL expressions

In his post, Proposed Tomcat Enhancement: Add flag to escape JSP’s EL by default, Matt Raible suggests that Tomcat should add an option to escape the output of EL expressions by default. At Trillian we’ve also run into the problem he’s describing since we needed the output of our JSPs to be valid XML at all times.

We ended up using a servlet filter which preprocesses all JSP files the first time they are executed. The filter uses an XSL which replaces all ${foo} occurrences with ${fn:escapeXml(foo)}. Obviously, the JSPs have to be written using the JSP XML syntax otherwise the XSL won’t to be able to process them.

Matt asked if I was willing to share this filter and I would be more than happy to do so. You will find the files attached.

Please note that I had to strip out some stuff from the files. Particularly the caching of the compiled XSL file since that involved lots of other code which I couldn’t strip down to a manageable size. It shouldn’t be too hard to implement this using your preferred caching library. I’m not 100% sure the Java files will compile but that shouldn’t be too hard to work out. Also, there’s lots of dependencies (commons-io, commons-logging, dom4j, spring, etc, all open source) that you might want to get rid of.

The JspPreprocessFilter will intercept any request for a JSP file. If that JSP hasn’t already been preprocessed it will rename the original file to .jsp.bak and then run it through the XSL producing the preprocessed .jsp file. The filter uses the modification time of the files to determine if a file has been changed and needs to be preprocessed again.

I’m using Spring to configure this filter which is why it takes its dependencies in the constructor and not isn’t configured using the init() method. I’m using org.apache.xalan.xsltc.trax.SmartTransformerFactoryImpl as SAXTransformerFactory implementation.

The XSL will match on all HTML attributes and text nodes and run their contents through the XalanUtil.escape() helper method. This method will find any EL expressions in the contents and change them as described above.

I hope this code will be of some use. (Ab)use it as you see fit. Eye-wink The only thing I’m asking is that you let me know if you spot some stupid mistake I’ve done or find a bug. Thanks!

2 thoughts on “Preprocessing JSP files to automatically escape EL expressions”

  1. It’s in the public domain. Feel free to use it anyway you like. I would appreciate if you let me know if you find a bug.

Comments are closed.