If you are using Spring Boot (tested with 3.0.4), then UTF-8 will work out of the box by default for both HTTP POST requests and responses.
If you have manually added Spring MVC, then you'll need to configure two things:
- CharacterEncodingFilter: a Spring Web servlet filter that allows you to:
specify a character encoding for requests. This is useful because current browsers typically do not set a character encoding even if specified in the HTML page or form.
- StringHttpMessageConverter: a Spring HttpMessageConverter that allows you to change the response
Content-Type
HTTP header field. Without this, the Content-Type
header will usually be text/html;charset=ISO-8859-1
instead of UTF-8.
How to set CharacterEncodingFilter?
It depends on your web app configuration. You should look into how you can set a Servlet Filter in general. For CharacterEncodingFilter
you'll need to set the encoding
param to utf-8
and the forceEncoding
to true
.
For example, if you are using web.xml
to configure Servlet Filters, then you could use something like this in your web.xml
:
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
If this doesn't work (meaning, your MVC controller doesn't receive request parameters as UTF-8), then you need to move the characterEncodingFilter
higher up in web.xml
, so that it gets called before other filters.
How to set StringHttpMessageConverter?
Change/add your WebMvcConfigurer
to something like this:
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class MyCustomWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
}
It uses StandardCharsets.ISO_8859_1
by default, but the code above will change it to UTF-8. You can verify if this is working, by checking the Content-Type
header in the HTTP responses. Which should now show text/html;charset=UTF-8
instead of text/html;charset=ISO-8859-1
.