JSP中的Escape EL,代表JSON数据 [英] Escape EL in JSP that represent JSON data

查看:142
本文介绍了JSP中的Escape EL,代表JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring控制器设置:

The Spring controller sets:

model.addAttribute("myJsonObj", JsonUtils.toJson(myObject));

JSP类似于:

<script>
  var myObj = ${myJsonObj};
  (...)

如何正确保护它不受任何XSS攻击?

How to properly protect this from any XSS exploit?

会破坏JSON(双引号等)

would break the JSON (double quotes, etc.)

在JSP中避免直接使用EL的正确策略是什么?

What's the right strategy to avoid directly EL in the JSP?

推荐答案

当JSP输出var myObj = ${myJsonObj};时,其行为与 eval 脚本相同,并导致XSS问题. 解决方案是将${myJsonObj}输出为字符串,因此不会执行恶意脚本. 然后使用JSON.parse()将字符串恢复为javascript对象,因此您无需更改其他脚本.

When JSP output var myObj = ${myJsonObj};, the behavior is the same as eval the script and cause XSS issue. The solution is output ${myJsonObj} as string, so malicious script will not execute. Then use JSON.parse() restore the string to javascript object, so you don't have to change other scripts.

以字符串形式输出${myJsonObj}时,必须处理双引号/单引号char. 可以使用JSP定制标记/EL函数来完成此操作,例如:

You have to handle the double/single quote char when output ${myJsonObj} as string. This can be done using a JSP custom tag/EL function, for example:

var myObj = JSON.parse('<my:escapeEcmaScript value="${myJsonObj}"/>');

或者在Spring控制器中完成

Or do it in Spring controller

model.addAttribute("myJsonObj", StringEscapeUtils.escapeEcmaScript(JsonUtils.toJson(myObject)));
//In JSP
//var myObj = JSON.parse('${myJsonObj}');

这篇关于JSP中的Escape EL,代表JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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