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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

43,752 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>