Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure CharacterEncodingFilter in SpringBoot?

I encountered some encoding problems in learning Spring Boot; I want to add a CharacterEncodingFilter like Spring 3.x. just like this:

<filter>
    <filter-name>encodingFilter</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>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
like image 673
navee Avatar asked Jun 05 '14 07:06

navee


People also ask

What is CharacterEncodingFilter?

CharacterEncodingFilter is a servlet filter that helps us to specify a character encoding for requests and responses. This filter is useful when browsers do not set a character encoding or if we want a specific interpretation for requests and responses.

What is spring FilterRegistrationBean?

FilterRegistrationBean registers a Filter as Spring bean and it provides methods to add URL mappings, set Filter order etc. When we register a Filter using Spring @Component , we can set Filter order using Spring @Order annotation but there is no way to change default URL mappings in this case.


2 Answers

Since Spring Boot 1.4.2 registering your own CharacterEncodingFilter will work ONLY IF you disable Spring's own instance of this bean by setting spring.http.encoding.enabled=false in the application.properties.

However, one can resolve this matter without any Filter instantiation by adding these setting to the application.properties:

# Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly. spring.http.encoding.charset=UTF-8 # Enable http encoding support. spring.http.encoding.enabled=true # Force the encoding to the configured charset on HTTP requests and responses. spring.http.encoding.force=true 

Source: Appendix A. Common application properties

like image 184
Fritz Duchardt Avatar answered Oct 24 '22 02:10

Fritz Duchardt


Example code for your Application.java class, as proposed in the comments above:

@Bean
public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setForceEncoding(true);
    characterEncodingFilter.setEncoding("UTF-8");
    registrationBean.setFilter(characterEncodingFilter);
    return registrationBean;
}
like image 39
mika Avatar answered Oct 24 '22 01:10

mika