开发者

c:out nested inside element attribute

开发者 https://www.devze.com 2023-04-13 07:01 出处:网络
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开发者_运维技巧

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).

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}"/>


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:

<input type="text" name="firstname" value="${fn:escapeXml(param.firstname)}"/>


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.

In your example, you could actually get away with no <c:out>:

<input type="text" name="firstname" value="${param.firstname}"/>

Edit: XSS issues

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.

<span>${esc:forHtml(sketchyText)}</span>
<span><esc:forHtml(sketchyText)/></span>
<input value="${esc:forHtmlAttribute(sketchyText)}"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号