I am going to avoid HTML in Spring MVC using Jackson Mapper to avoid an XSS attack.
I'm only looking to slip away with Jackson and how to set up Jackson in Spring.
I tried to export json with text like "<" ">", I expect to get out of them before < and >
for example, I added text enclosed with a bold <b> , I expect to see plain text in the text at the top end of the html, but at the end the text will be highlighted in bold on the front-end html page.
Below is my approach, I do not know why this did not work.
Anyone can help?
Thanks in advance!
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['<'] = 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) { return null; } }
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <array> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="objectMapper"> <bean class="xyzCustomObjectMapper" /> </property> </bean> </array> </property> </bean>
code>
source share