@InitBinder
public void initBinder(final WebDataBinder webdataBinder) {
//去除首尾空格
webdataBinder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(htmlUtils.htmlEscape(text, "UTF-8"));
}
});
}
1.自定义string 反序列化实现
public final class JsonStringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String text = jsonParser.getText();
return HtmlUtils.htmlEscape(text, "UTF-8");
}
}
2.配置反序列化类
@Configuration
public class BaseMvcConfig implements WebMvcConfigurer {
@Override
public 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传到前端丢失精度。这个是很大的坑。