1.針對(duì)url傳參或form表單傳參
@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"));
}
});
}
2.針對(duì)Body的JSON格式傳參
1.自定義string 反序列化實(shí)現(xiàn)
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;
}
}
順便說一下,序列化的設(shè)置一定要把Long轉(zhuǎn)成String。因?yàn)閖s對(duì)Long類型支持的精度不夠,導(dǎo)致后端使用的Long傳到前端丟失精度。這個(gè)是很大的坑。