Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

1. Overview

In this article, we'll learn about CharacterEncodingFilter and it's usage in a Spring Boot application.

2. 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.

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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!