我应该在哪里转义HTML字符串,JSP页面或Servlets? [英] Where should I escape HTML strings, JSP page or Servlets?

查看:155
本文介绍了我应该在哪里转义HTML字符串,JSP页面或Servlets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望为我提供一套明确的指导方针或处理逃避字符串的裁决。我用来转义字符串的是apache commons-lang-x.x.jar库。特别是 StringEscapeUtils.escapeHtml(String toEscape)方法。

I would appreciate providing me with a set of clear guidelines or ruling for handling escaping strings. What I use for escaping strings is the apache commons-lang-x.x.jar library. Specifically the StringEscapeUtils.escapeHtml(String toEscape) method.

我需要知道:

(1)在JSP页面或Servlet中转义字符串更好?

(1) Where is it better to escape strings, on the JSP page or in the Servlet?

(2)你是什么?推荐StringEscapeUtils.escapeHtml(..)或< c:out>来自JSTL

(2) What do you recommend StringEscapeUtils.escapeHtml(..) or <c:out> from JSTL

(3)处理多行字符串,这是更好的,使用< br>直接在字符串中,或​​\ n和nl2br()方法:

(3) Handling multiline strings, which is better, use <br> directly in the string, or \n and a nl2br() method:

字符串strError =用户名无效。\\ n请再试一次。 ;

String strError =用户名无效。< br>请重试。;

(4)如何转义接收通配符的字符串,例如:

(4) How would I go escaping strings that receive wild cards, example:

String strError =无效的用户[%s]。< br>请指定其他用户。

(5)由于javascript转义字符不同。我应该使用什么来转义要在JSP页面的javascript部分内呈现的Java字符串(例如 var name =<%= javaStringHoldingName%> )。

(5) Since javascript escape characters are different. What should I use to escape Java strings that are to be rendered inside the javascript sections of the JSP page (eg. var name = "<%=javaStringHoldingName%>").

推荐答案

你只需将它完全转移到可能受到伤害的地方。在这种特殊情况下,它在视图中。当用户控制的HTML在视图中的所有HTML中进行内联时,可能会受到损害。这是XSS的源代码。

You only need to escape it exactly there where it can harm. In this particular case, it's in the view. User-controlled HTML can harm when it get inlined among all your HTML in the view. This is a source for XSS.

在设计良好的JSP页面中(读取: scriptlets ),JSTL为您提供< c:out> tag和 fn:escapeXml()用于转义HTML / XML的函数。

In a well-designed JSP page (read: no scriptlets), JSTL offers you the <c:out> tag and fn:escapeXml() function to escape HTML/XML.

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

这篇关于我应该在哪里转义HTML字符串,JSP页面或Servlets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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