How to make JSP UTF-8 support ? Solution for proper display of UTF-8 in JSP

The method setCharacterEncoding of the ServletRequest / HttpServletRequest interface is used to set the encoding (UTF-8) of any request data.  This method must be called prior to parsing any post data or reading any input from the request. To do this, we can create a filter class that implements the Filter interface, and set the encoding  of request to UTF-8 as given in the UTF8Filter class.

package Filters;


import javax.servlet.*;

public class UTF8Filter implements Filter


    public void destroy(){}

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


      request.setCharacterEncoding("UTF-8"); // encodes the charater in UTF-8 format.



   public void init(FilterConfig filterConfig) throws ServletException{}



UTF8Filter class will be mapped in the web.xml file for all the requests as given below


<filter >





	<filter-name>UTF8Filter </filter-name>

	<url-pattern >/*</url-pattern>


If an encoding is not specified by the client request, the web container uses a default encoding to parse request parameters. Suppose If the client has not set character encoding and the request parameters are encoded with a different encoding other than the default, the parameters will be parsed incorrectly.

In JSP,  we need to set the content type charset to UTF-8  as given below.

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"errorPage="Error.jsp" % >

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/ > 

Now the browser will display the response data with the proper UTF-8 format.

Reference : SetCharacterEncodeing