Home » java » Java Best Practices to Prevent Cross Site Scripting

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not duringprocessing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib tag or fn:escapeXml function for this. E.g.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>
and
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">
That’s it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).
If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it’s all spread over the business code and/or in the database. That’s only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become & instead of & so that the enduser would literally see & instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

Leave a comment