Thursday, March 12, 2009

Changing Default character encoding scheme of Tomcat

Default URI encoding in Apache Tomcat is ISO-8859-1. There are many ways that we can change this encoding. i did this by writing my own filter. Code is as follows:

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingFilter implements Filter {

@SuppressWarnings("unused")
private FilterConfig filterConfig = null;
private String param;

public void destroy() {
this.filterConfig = null;
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {

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

if (null != this.param) {
// instead of making these values hardcode we can supply these values from web.xml using init-param
response.setContentType("text/html; charset=ISO-8859-1");
request.setCharacterEncoding("ISO-8859-1");

chain.doFilter(request, response);

//do it again, since JSPs will set it to the default
response.setContentType("text/html; charset=ISO-8859-1");
request.setCharacterEncoding("ISO-8859-1");
}
}

public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
}

No comments:

Post a Comment