如何通过杰克逊生成器html转义值 [英] How to html escape values by Jackson generator

查看:139
本文介绍了如何通过杰克逊生成器html转义值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用Spring及其内置的MappingJacksonHttpMessageConverter生成大量JSON对象。好极了。

We generate lots of JSON objects using Spring and its built-in MappingJacksonHttpMessageConverter . All great.

但是现在我想 html转义我的(任何类型)对象的字符串值以防止XSS。

But now I want to html escape String values of my (any kind of) objects in order to prevent XSS.

那么,我该如何处理这个问题呢?我首先想到我可以编写一个自定义的Object mapper并将其放入MappkingJacksonHttpMessageConverter中。但是,writeValue需要一个Object,我不希望这样,我想让它的字段进行迭代。我打赌杰克逊转换器也需要这样做,而不是自己这样做。所以我想影响那个部分。

So, how do i approach this problem? I first thought I could write a custom Object mapper and put it into the MappkingJacksonHttpMessageConverter. However, the writeValue takes an Object, and I don't want that, I want to have its fields to iterate over. Instead of doing that myself, I bet the jackson converter needs to do that as well. So i want to influence that part.

现在我最终得到了一个SerializerProvider接口。 ObjectMapper调用标准实现(StdSerializerProvider)。所以在某处,我想覆盖/影响负责设置值的方法。

Now I end up with a SerializerProvider interface. The standard implementation (StdSerializerProvider) is getting called by the ObjectMapper. So somewhere there I want to override/influence the method that is responsible for setting values.

这可能吗?据我所知,很难扩展。我无法覆盖StdSerializerProvider来覆盖ObjectMapper使用的方法。也许我需要覆盖另一个?

Is that possible? As far as I can see it is hard to extend. I cannot override the StdSerializerProvider to override the method that ObjectMapper uses. Perhaps I need to override another one?

或者,这可能是完全错误的,我需要从一个完全不同的角度来看待它?

Or, perhaps this is totally wrong and I need to approach it from a totally different angle?

有什么想法吗?

哦顺便说一句,自己实现SerializerProvider并创建一个委托给StdSerializerProvider的composit,可能是可能的,但我宁愿不这样做。 (我已经在自己实例化StdSerializerProvider时遇到了问题)。

Oh btw, implementing the SerializerProvider myself and creating a composit that delegates to the StdSerializerProvider, might be possible but I'd rather not to. (i already have problems instantiating the StdSerializerProvider myself).

任何想法都表示赞赏!

推荐答案

有多种方法,具体取决于您如何识别要逃避的事物。一些想法:

There are multiple ways, depending on how you can identify things you want to escape. Some thoughts:


  • 如果你想引用/转义所有字符串,你可以定义自定义字符串序列化器

  • 您可以首先序列化为JSON树(JsonNode) - ObjectMapper.convertValue(pojo,JsonNode.class) - 修改它,然后序列化为JSON(ObjectMapper.writeValue(intermediateTree))

  • 如果你想要一个灵活的系统,你可以为需要特殊处理的字段添加注释,你可以使用ContextualSerializers的Jackson 1.7功能;自定义序列化程序,可以根据注释重新配置自身。一开始可能看起来有些过分,但这可以用来轻松指定自定义修饰符(值为Class的注释属性,表示序列化程序可以调用以修改被序列化的值的对象 - 比如转义)

这篇关于如何通过杰克逊生成器html转义值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆