Wednesday, May 5, 2021

Spring Boot: escape HTML and non-ASCII characters in Json response


Create an ObjectMapper object and let Spring Boot use our ObjectMapper object with the @Bean and @Primary annotations.

In our configuration bean:

@Configuration
public class MyConfiguration {
 
  @Bean
  @Primary
  public ObjectMapper objectMapper() {
    // create our own ObjectMapper object.
    ObjectMapper objMapper = new ObjectMapper();
 
    // escape all non-ASCII characters
    objMapper.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);

    // definition of the HTML characters to escape
    final class HtmlCharsToEscape extends CharacterEscapes
    {
      private final int[] asciiEscapes;
    
      public
HtmlCharsToEscape()
      {
        // get the set of default escaped characters (double-quote, backslash etc)
        int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
        // and force escaping of HTML special characters:
        esc['<'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['>'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['&'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
        asciiEscapes = esc;
      }

      @Override public int[] getEscapeCodesForAscii() {
        return asciiEscapes;
      }

      @Override public SerializableString getEscapeSequence(int ch) {
        // no CUSTOM escaping needed:
        return null;
      }
    }

    // Escape the HTML special characters.
    objMapper.getFactory().setCharacterEscapes(new
HtmlCharsToEscape());
 
    // This will be picked up the Spring Boot.
    return objMapper; 
  }
}



No comments:

 
Get This <