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>


Externalize of properties file in Tomcat

Below is the approach that can be used for externalize ApplicationResource properties file in Tomcat 7 & 9.


Steps:

1.       The change needs to be done in <tomcat_installation_path>/conf/Catalina/localhost/<APP_NAME>.xml (where data sources are defined)
2.       E.g. ApplicationResource.properties file is kept in D:/AppProperties/TestApp path

3.       For Tomcat 7.x , need to add the folder in classpath by using below tag under <Context> tag
a.       <Resources className="org.apache.naming.resources.VirtualDirContext"
               extraResourcePaths="/WEB-INF/classes=D:/AppProperties/TestApp"/>

4.       For Tomcat 8.x/9.x, you can provide the properties file instead of directory itself, by using below tag under <Context> tag
a.       <Resources>
    <PreResources className="org.apache.catalina.webresources.FileResourceSet"
            base="D:/AppProperties/TestApp/ApplicationResource.properties"
            webAppMount="/WEB-INF/classes/ApplicationResource.properties" />
     </Resources>

b. Alternatively, to configure directory the below one can be used

<Resources>
<PreResources className="org.apache.catalina.webresources.DirResourceSet"
base="D:/AppProperties/TestApp"
webAppMount="/WEB-INF/classes"/>

</Resources>
5.       This will load the properties file from the external location; hence remove the properties file from WEB-INF/classes

Convert Java Project from Log4j 1 to Log4j2

Many times while working on old Java projects we find Log4j 1.x is used. But as the Log4j2 is the new one; hence to upgrade to Log4j2 we nee...