Thursday, June 18, 2009

Special characters in web application

I've been adding text resources in my application so as to display the web application in differnt languages. The problem I faced was that whenever a special characted comes the browser display's "?". The browser is not able to display the special character inspite of selecting UTF-8 language.

So I made some changes in the code to handle UTF-8 character set.

Make sure that all JSP pages have
<%@ page contentType="text/html; charset=UTF-8"%>

In case if you are having html pages, use meta tag to add character set information.
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

Second, Make changes in the server's configuraton file. I am using Sun's web server. So in my sun-web.xml file I added <parameter-encoding default-charset="UTF-8"/> to look like

<sun-web-app>
<parameter-encoding default-charset="UTF-8"/>
.
.
</sun-web-app>

In case of apache tomcat, you have specify URIEncoding attribute in Connector tag in server.xml.

But this is what something server will be handling, and it's in not our hand. To make sure that application uses UTF-8 character set, a filter can bge added to web application.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.FilterChain;

import java.io.IOException;

public class CharacterEncodingFilter implements Filter
{

private FilterConfig fc;

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
{

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

response.setContentType("text/html; charset=UTF-8");
request.setCharacterEncoding("UTF8");

chain.doFilter(request, response); //do it again, since JSPs will set it to the default

response.setContentType("text/html; charset=UTF-8");
request.setCharacterEncoding("UTF8");
}

public void init(FilterConfig filterConfig)
{

this.fc = filterConfig;
}

public void destroy()
{

this.fc = null;
}
}

Once you are done writiing the java class, add the filter configuration to the web.xml file.

<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.its.struts.action.CharacterEncodingFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>


That's all !!! :)

No comments: