开发者

Where should I escape HTML strings, JSP page or Servlets? [duplicate]

This question already has answers here: XSS prevention in JSP/Servlet web application (10 answers) Closed 7 years ago.

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.

I need to know:

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

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

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

String strError = "Invalid username.\nPlease try again.";

or

String strError = "Invalid username.<br>Please try again.";

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

String strError = "Invalid user [%s].<br>Please specify another user."

(5) Since javascript escape characters are开发者_如何学Python 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%>").


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.

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


For two of your questions:

1) Escaping strings for display purposes - I would consider this a view concern. Your JSP could handle this, if you're using your JSP as a view.

3) Error messages from your models / business logic layer should not include formatting such as newline characters. Let your view determine how to format error messages. With HTML, the use of a div tag with appropriate width styling can eliminate the need for br tags, for example.


I would probably not pass a String object, but instead just pass an error object up to the view and let the jsp do whatever it wants

In the controller:

errorObj.name = "invalid login";
errorObj.description = "try again";

In the view:

<c:out value="${errorObj.name}" /><br /><c:out value="${errorObj.description}" />

Not really related to your question, but it's also a good practice to use a message like, "invalid login attempt" no matter what the login error really is. The message you are giving, "invalid username" lets someone intent on hacking your accounts know if they have a good username that they can use to then attack the password with. If this is exposed publicly, this can be a small, but very real, issue.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜