How do I prevent people from doing XSS in Spring MVC?

Doug picture Doug · Jan 27, 2010 · Viewed 98.4k times · Source

What should I do to prevent XSS in Spring MVC? Right now I am just putting all places where I output user text into JSTL <c:out> tags or fn:escapeXml() functions, but this seems error prone as I might miss a place.

Is there an easy systematic way to prevent this? Maybe like a filter or something? I'm collecting input by specifying @RequestParam parameters on my controller methods.

Answer

Tendayi Mawushe picture Tendayi Mawushe · Jan 27, 2010

In Spring you can escape the html from JSP pages generated by <form> tags. This closes off a lot avenues for XSS attacks, and can be done automatically in three ways:

For the entire application in the web.xml file:

<context-param>
    <param-name>defaultHtmlEscape</param-name>
    <param-value>true</param-value>
</context-param>

For all forms on a given page in the file itself:

<spring:htmlEscape defaultHtmlEscape="true" /> 

For each form:

<form:input path="someFormField" htmlEscape="true" />