Web applications are increasing day by day. Have you ever faced an issue of displaying dodgy characters on the web page, If so, it could be because of the character set of your web application server. Here I'm going to explain about the character encoding filter which could be very handy if you want to convert your output into a desired characters encoding format.

Normally, Servlets and JSPs will use the default character set that has been chosen while installing the web container. If you want to modify the character set for your Servlet or JSP, you need to implement below filter in your web application

Note: since this character encoding is implemented as a filter, it will not have an impact on any of your application functionality.

Create this class under your application:
package cmi.util;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
* This filter can be used to set the content type as UTF-8.
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 20th April 2008
*/

public class RequestEncodeFilter implements Filter
{
//FilterConfig object
private FilterConfig filterConfig=null;

//Default constructor
public RequestEncodeFilter()
{
System.out.println("Request response encoder Filter object has been created");
}

//Intitialization method
public void init(FilterConfig filterConfig)
{
this.filterConfig=filterConfig;
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
//Setting the character set for the request
request.setCharacterEncoding("UTF-8");

// pass the request on
chain.doFilter(request, response);

//Setting the character set for the response
response.setContentType("text/html; charset=UTF-8");
}

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

In the above code, replace "UTF-8" with your character set you wish to convert. You need to map this filter in web.xml as mentioned below

<filter>
<filter-name>requestEncodeFilter</filter-name>
<filter-class>cmi.util.RequestEncodeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestEncodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
That's it... you'll get the output as required.