Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jsp

servlets

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

like image 226
Basil Musa Avatar asked Feb 09 '11 17:02

Basil Musa


2 Answers

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)}" />
like image 116
BalusC Avatar answered Nov 15 '22 17:11

BalusC


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.

like image 37
Shan Plourde Avatar answered Nov 15 '22 15:11

Shan Plourde