Use response encoding when escaping HTML

With SPR-9293, it is now possible to HTML escape text while taking into
account the current response encoding. When using UTF-* encodings, only
XML markup significant characters are escaped, since UTF-* natively
support those characters.

This commit adds a new servlet context parameter to enable this fix by
default in a Spring MVC application:

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

Issue: SPR-12350, SPR-12132
This commit is contained in:
Brian Clozel
2014-10-24 11:46:09 +02:00
parent 73e398a165
commit a0c210457b
9 changed files with 124 additions and 17 deletions

View File

@@ -106,6 +106,12 @@ public abstract class WebUtils {
*/
public static final String HTML_ESCAPE_CONTEXT_PARAM = "defaultHtmlEscape";
/**
* Use of response encoding for HTML escaping parameter at the servlet context level
* (i.e. a context-param in {@code web.xml}): "responseEncodedHtmlEscape".
*/
public static final String RESPONSE_ENCODED_HTML_ESCAPE_CONTEXT_PARAM = "responseEncodedHtmlEscape";
/**
* Web app root key parameter at the servlet context level
* (i.e. a context-param in {@code web.xml}): "webAppRootKey".
@@ -175,7 +181,9 @@ public abstract class WebUtils {
* (if any). Falls back to {@code false} in case of no explicit default given.
* @param servletContext the servlet context of the web application
* @return whether default HTML escaping is enabled (default is false)
* @deprecated as of Spring 4.1, in favor of {@link #getDefaultHtmlEscape}
*/
@Deprecated
public static boolean isDefaultHtmlEscape(ServletContext servletContext) {
if (servletContext == null) {
return false;
@@ -202,6 +210,26 @@ public abstract class WebUtils {
return (StringUtils.hasText(param)? Boolean.valueOf(param) : null);
}
/**
* Return whether response encoding should be used when HTML escaping characters,
* thus only escaping XML markup significant characters with UTF-* encodings.
* This option is enabled for the web application with a ServletContext param,
* i.e. the value of the "responseEncodedHtmlEscape" context-param in {@code web.xml}
* (if any).
* <p>This method differentiates between no param specified at all and
* an actual boolean value specified, allowing to have a context-specific
* default in case of no setting at the global level.
* @param servletContext the servlet context of the web application
* @return whether response encoding is used for HTML escaping (null = no explicit default)
*/
public static Boolean getResponseEncodedHtmlEscape(ServletContext servletContext) {
if (servletContext == null) {
return null;
}
String param = servletContext.getInitParameter(RESPONSE_ENCODED_HTML_ESCAPE_CONTEXT_PARAM);
return (StringUtils.hasText(param)? Boolean.valueOf(param) : null);
}
/**
* Return the temporary directory for the current web application,
* as provided by the servlet container.