UTF-8 encoding on J2EE

A 3 step method to apply UTF-8 encoding to J2EE applications.

1. Add the following directives to the page included in ALL jsps.

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page pageEncoding="UTF-8"%>

This will add request headers and meta-tags to every page served which will tell the browser that the page is utf-8 encoded.

2. Add a filter at server side to encode the request body received to UTF-8. A spring UTF-8 encoder (available in org.springframework.web*.jar of spring 3 distribution) if used, will have the following changes 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>
</filter>
<filter-mapping>
			<filter-name>encodingFilter</filter-name>
			<url-pattern>/*</url-pattern>
</filter-mapping>

3. Tell the container that the URLs too are to be encoded in UTF-8. In tomcat, this is done by adding the attribute URIEncoding=UTF-8 to the connector tag in server.xml. Else, this can also be done by setting useBodyEncodingForURI=true in the connector tag. This will tell the connector to use the same encoding used for the request body (set to UTF-8 in the previous steps.) This will make sure that the parameters received via GET requests too are properly understood by the application.

Sreekumar Kj
Sreekumar (KJ) has been a hobby programmer from school days. Codemarvels is his personal blog from the year 2010, where he writes about technology, philosophy, society and a bit about physics. He now runs a conversational AI company - DheeYantra - focusing his efforts to help businesses improve operational efficiency using digital employees powered by AI.