<返回更多

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

2022-06-24    杭漂周星星
加入收藏

1.针对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.针对Body的JSON格式传参

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传到前端丢失精度。这个是很大的坑。

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>