title: HTML escape with Spring MVC and Jackson Mapper
body: <p>I am going to escape HTML in Spring MVC with Jackson Mapper to avoid XSS attack.<br><br>
  I search for escaping with Jackson alone and how to config Jackson in Spring.<br>
  I tried export json with text like "&lt;" ">", I expect to escape them to <code>&amp;#60;</code> and <code>&amp;#62;</code><br><br>
  for example I added some text enclosed with "bold tag" <code>&lt;b&gt;</code>, I expect to see plain bold tag text in the front end html but end up the text is shown in bold style in the front end html page.</p>
  
  <p>Below is my approach, I don't know why it didn't work out. </p>
  
  <p>Anyone can help?</p>
  
  <p>Thanks in advance!</p>
  
  <pre><code>public class CustomObjectMapper extends ObjectMapper {  
      public CustomObjectMapper() {
          this.getJsonFactory().setCharacterEscapes(new CustomCharacterEscapes());
      }
  }
  
  public class CustomCharacterEscapes extends CharacterEscapes {
      private final int[] asciiEscapes;
  
      public CustomCharacterEscapes() {
          int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
          esc['&lt;'] = CharacterEscapes.ESCAPE_STANDARD;
          esc['&gt;'] = CharacterEscapes.ESCAPE_STANDARD;
          esc['&amp;'] = CharacterEscapes.ESCAPE_STANDARD;
          esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
          asciiEscapes = esc;
      }
  
      @Override
      public int[] getEscapeCodesForAscii() {
          return asciiEscapes;
      }
  
      @Override
      public SerializableString getEscapeSequence(int ch) {
          return null;
      }
  }
  </code></pre>
  
  <p><pre><code></p>
  
  <pre><code>&lt;bean
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt;
      &lt;property name="messageConverters"&gt;
          &lt;array&gt;
              &lt;bean id="jsonConverter"
                  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;
                  &lt;property name="objectMapper"&gt;
                      &lt;bean class="x.y.z.CustomObjectMapper" /&gt;
                  &lt;/property&gt;
              &lt;/bean&gt;
          &lt;/array&gt;
      &lt;/property&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p></pre></code></p>