如何让Jackson在输出字符串中转义?(How to get Jackson to escape a in output string?)

编程入门 行业动态 更新时间:2024-10-27 13:25:10
如何让Jackson在输出字符串中转义?(How to get Jackson to escape a in output string?)

我有一个简单的Java对象,我正在使用Jackson序列化为JSON,然后我将其放入JSP页面中的<script>标记中,作为初始化JavaScript对象的一部分。 例如

<script>SomeLib.load(${someObject});</script>

除非 someObject的某个字段是包含"</script>"的字符串, 否则这很有效,因为这个问题 。 也就是说,如果输出看起来像这样:

<script>SomeLib.load({"someValue":"hacked!</script>"});</script>

那么浏览器(到目前为止在Chrome和FF中都经过测试)在hacked!后认为</script>标签hacked! 正在关闭脚本标记。 这打破了JavaScript并让"});</script>对用户可见。

有没有办法让杰克逊以某种方式逃避这个价值来解决这个问题?

I have a simple Java object that I'm using Jackson to serialize to JSON, and then I'm dropping that into a <script> tag in my JSP page as part of initializing a JavaScript object. e.g.

<script>SomeLib.load(${someObject});</script>

This works great unless one of the fields of someObject is a String that contains "</script>", because of this issue. That is, if the output looks like this:

<script>SomeLib.load({"someValue":"hacked!</script>"});</script>

then the browser (tested in both Chrome and FF so far) believes the </script> tag after hacked! is closing the script tag. Which breaks the JavaScript and leaves "});</script> visible to the user.

Is there a way to get Jackson to escape that value in some fashion that will fix this problem?

最满意答案

拉维斯回答错了。 在那里看我的评论。

更好的方法是使用反斜杠转义斜杠</ :

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> ... <script>SomeLib.load(${fn:replace(jsonString, "</", "<\\/")});</script>

注意:需要两个反斜杠,因此第一个在JSP语法中进行转义。

好的部分是,它不需要特殊的解码。

PS:要在杰克逊方面这样做,请参阅此博客 - 它涵盖了逃避其他角色,但只是在列表中添加斜线以逃避(全部)斜线字符。

Ravis answer is wrong. See my comment there.

A better way is to escape the slash in </ with a backslash, like:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> ... <script>SomeLib.load(${fn:replace(jsonString, "</", "<\\/")});</script>

Note: two backslashes are needed so the first one is escaped in the JSP syntax.

The good part is, it needs no special decoding.

PS: To do it on Jackson side, see this blog - it covers escaping other characters, but just add slash to the list to escape (all) slash characters.

更多推荐

本文发布于:2023-07-09 00:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082146.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Jackson   escape   string   output

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!