简单配置spring mvc,防止xss注入

1.针对url传参或form表单传参@InitBinderpublic void initBinder(final WebDataBinder webdataBinder) {//去除首尾空格webdataBinder.registerCustomEditor(String.class, new PropertyEditorSupport() {@Overridepublic void setAsText(String text) throws IllegalArgumentException {setValue(htmlUtils.htmlEscape(text, "UTF-8"));}});}2.针对Body的JSON格式传参【简单配置spring mvc,防止xss注入】1.自定义string 反序列化实现
public final class JsonStringDeserializer extends JsonDeserializer<String> {@Overridepublic String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {String text = jsonParser.getText();return HtmlUtils.htmlEscape(text, "UTF-8");}}2.配置反序列化类
@Configurationpublic class BaseMvcConfig implements WebMvcConfigurer {@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {MAppingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();ObjectMapper objectMapper = new ObjectMapper();objectMapper.registerModule(getSimpleModule());jackson2HttpMessageConverter.setObjectMapper(objectMapper);converters.add(0, jackson2HttpMessageConverter);}private SimpleModule getSimpleModule() {SimpleModule simpleModule = new SimpleModule();simpleModule.addSerializer(Long.class, ToStringSerializer.instance);simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);//配置反序列化类simpleModule.addDeserializer(String.class, new JsonStringDeserializer());return simpleModule;}}顺便说一下,序列化的设置一定要把Long转成String 。因为js对Long类型支持的精度不够,导致后端使用的Long传到前端丢失精度 。这个是很大的坑 。




    推荐阅读