1. Overview
In this article, we’ll learn about CharacterEncodingFilter and it’s usage in a Spring Boot application.
2. CharacterEncodingFilter
3. Implementation
Let’s see how we can configure this filter in a Spring Boot application.
First, let’s create a CharacterEncodingFilter:
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
In our example, we have set the encoding as UTF-8. But, we can set any other encoding based on the requirement.
We have also used forceEncoding attribute to enforce the encoding irrespective of its presence in request from the browser. Since this flag is set as true, the provided encoding will also be applied as response encoding.
Finally, we’ll register the filter with FilterRegistrationBean which provides configuration to register Filter instances as part of the filter chain:
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns("/*");
return registrationBean;
In non-spring boot applications, we can add this filter in the web.xml file to get the same effect.
4. Conclusion
In this article, we’ve described the need for CharacterEncodingFilter and seen an example of its configuration.
As always, the complete code for this article is available over on GitHub.