java c:out 嵌套在元素属性里面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7771949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c:out nested inside element attribute
提问by Ryan
Is nesting a c:out JSTL tag inside an element attribute a good practice or is using the var attribute of c:out generally preferred? It seems to work either way, but I suspect nesting it might not work in some application servers or versions of JSP (and it just looks wrong).
在元素属性中嵌套 ac:out JSTL 标记是一个好习惯还是使用 c:out 的 var 属性通常是首选?无论哪种方式它似乎都可以工作,但我怀疑嵌套它在某些应用程序服务器或 JSP 版本中可能不起作用(而且它看起来是错误的)。
For example, an input element which has its value restored on validation failure, and with special character escaping:
例如,一个输入元素在验证失败时恢复其值,并带有特殊字符转义:
<input type="text" name="firstname" value="<c:out value="${param.firstname}"/>"/>
versus:
相对:
<c:out value="${param.firstname}" var="firstname"/>
<input type="text" name="firstname" value="${firstname}"/>
回答by BalusC
The common practice to prevent XSS attacks in HTML element attributes without disturbing the well formed XML syntax by a nested <c:out>
tag is using fn:escapeXml()
function instead:
在不通过嵌套<c:out>
标签干扰格式良好的 XML 语法的情况下防止 HTML 元素属性中的 XSS 攻击的常见做法是使用fn:escapeXml()
函数:
<input type="text" name="firstname" value="${fn:escapeXml(param.firstname)}"/>
回答by RustyTheBoyRobot
I usually use the ${}
everywhere that I can. It's simple and more readable. I use <c:out>
when I need the extra functionality, such as the escapeXml
function.
我通常会在${}
任何可能的地方使用。它简单且更具可读性。我<c:out>
在需要额外功能时使用,例如escapeXml
函数。
In your example, you could actually get away with no<c:out>
:
在您的示例中,您实际上可以逃脱no<c:out>
:
<input type="text" name="firstname" value="${param.firstname}"/>
Edit: XSS issues
编辑:XSS 问题
My answer does not address the XSS holes that BalusC and StuartWakefield mention. Although my answer is simplistically correct, you really should always mitigate XSS holes. I prefer to use the OWASP taglib.
我的回答没有解决 BalusC 和 StuartWakefield 提到的 XSS 漏洞。尽管我的回答简单正确,但您确实应该始终减少 XSS 漏洞。我更喜欢使用OWASP taglib。
<span>${esc:forHtml(sketchyText)}</span>
<span><esc:forHtml(sketchyText)/></span>
<input value="${esc:forHtmlAttribute(sketchyText)}"/>