bookmark_borderPrevent cross-site scripting when using JSON objects using ESAPI and Jackson framework 1.7.x





  1. Create a Custom Object Mapper and wire into Spring
  2. Create a JsonSerializer that encodes HTML (using ESAPI)
  3. Register the JsonSerializer in the CustomObjectMapper

Create a Custom Object Mapper and wire into Spring


public class CustomObjectMapper extends {




<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
	<property name="webBindingInitializer">
	<bean class="">
	<property name="messageConverters">
			<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
			<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
			<bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
			<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
			<ref bean="MappingJacksonHttpMessageConverter"/>


Create a JsonSerializer that encodes HTML (using ESAPI)



public class JsonHtmlXssSerializer extends JsonSerializer {

      if (value != null) {
         String encodedValue = encodeHtml(value);


So this class extends from, and implements its own serialize method. The method encodeHtml will use the ESAPI encoding functions to escape HTML.


Implementing this is very easy:

   protected String encodeHtml(String html) {
      DefaultEncoder encoder = new DefaultEncoder();
      return encoder.encodeForHTML(html);

The defaultEncoder is from ESAPI allowing us to encode the HTML.


Register the JsonSerializer in the CustomObjectMapper


public class CustomObjectMapper extends {

   public CustomObjectMapper() {
      module.addSerializer(new JsonHtmlXssSerializer());

bookmark_borderDon’t forget your resources directory! (Maven/Eclipse/Sysdeo-tomcat)

Recently I had to set up a XMLRPC Server. Using Apache’s XMLRPC it should not be that hard to set up.

It wasn’t. But it did not work the first time.

The XMLRPC Serlvet would not be initialized properly because it could not find the file. I was a bit suprised, because I had it in my src/main/org/apache/xmlrpc/webserver path… so why did it not work?

The reason is that whenever you run your Tomcat webserver, configured to look into your project directory (using the tomcat-sysdeo maven plugin) which is set up using maven; you’ll be using your classpath as set up there. If you look into your project->build path settings (tab source), you’ll see that everything under src/main is only including **/*.java, meaning it will not find the properties file at all!

Once I moved the to src/main/resources/org/apache/xmlrpc/webserver (where it belongs), it worked fine.

So remember, classpath, classpath, classpath!