Friday, April 12, 2019

UTF-8 encoding issue in Response in Tomcat


I have observed UTF-8 encoding issue for JSON response in Tomcat. By default tomcat uses ISO-8859-1. Below are the solution approaches:


Tomcat response (response is appended with ISO-8859-1 charset by Tomcat)
Content-Type: application/json;charset=ISO-8859-1

Solution:
Approach #1:
Add the below code in custom filter or servlet before sending the response

response.setCharacterEncoding("UTF-8");

Approach #2: (Better approach)
Use filter provided by Spring framework as mentioned below; which make the response to UTF-8 (Can add any other charset also).
Please add the below part in web.xml. The respective jar exists in spring-web dependency module.

Snippet to add in web.xml:

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


3 comments:

Reshma said...

Reshma said...

Amazing Post. keep update more information.
Java Training in Bangalore
Java classes in pune

Anonymous said...

Great, post is so informative and helpfull to everyone , keep posting and checkout my blog java course in pune

Java Vulnerability Scan

To get the list of vulnerable dependencies along with transitive dependencies SBOM is required to be generated first. Then on top of SBOM Gr...