Update Content-Type
based on encoding
in MVC FreeMarkerView
#33119
Description
Overview
As I mentioned in #33071 (comment), if you set the default encoding
in FreeMarkerConfigurer
and use FreeMarkerViewResolver
to resolve a FreeMarkerView
, Spring MVC currently does not update the charset
of the Content-Type
header of the HTTP response to reflect the actual type of encoding
used to read the template file and render the body of the response.
Specifically, if you don't specify the content type via the FreeMarkerViewResolver
, "text/html;charset=ISO-8859-1"
will be used, which is the default set in AbstractView
, and that can cause issues if templates are read and rendered using UTF-8 or some other explicit encoding.
As discussed in #33071, users may reasonably expect that an explicit encoding
(set in FreeMarkerConfigurer
) will be used as the charset
of the Content-Type
header of the HTTP response by default, unless the user explicitly overrides that via FreeMarkerViewResolver#setContentType
.
Luckily, FreeMarker 2.3.26 introduced Configuration#isDefaultEncodingExplicitlySet()
which "Tells if setDefaultEncoding(String)
(or equivalent) was already called on this instance, or it just holds the default value." By checking that, we can therefore reliably update the charset
of the Content-Type
header of the HTTP response to reflect the actual type of encoding
used to read the template file and render the body of the response, as long as the user explicitly set the desired default encoding via FreeMarkerConfigurer
.
Note, however, that the same logic cannot be reliably applied to the FreeMarker support in WebFlux since the WebFlux infrastructure automatically sets the default encoding to UTF-8.
Related Issues
- Improve documentation regarding encoding in FreeMarker support #33071
- Set
output_encoding
inFreeMarkerView
implementations #33106
Deliverables
- Update
Content-Type
based on explicit defaultencoding
inFreeMarkerView
in Spring MVC. - Update documentation to point out that FreeMarker 2.3.26 is the new minimum baseline for Spring Framework 6.2.