How to set request encoding in Tomcat?

Solution 1:

The request.setCharacterEncoding("UTF-8"); only sets the encoding of the request body (which is been used by POST requests), not the encoding of the request URI (which is been used by GET requests).

You need to set the URIEncoding attribute to UTF-8 in the <Connector> element of Tomcat's /conf/server.xml to get Tomcat to parse the request URI (and the query string) as UTF-8. This indeed defaults to ISO-8859-1. See also the Tomcat HTTP Connector Documentation.

<Connector ... URIEncoding="UTF-8">

or to ensure that the URI is parsed using the same encoding as the body1:

<Connector ... useBodyEncodingForURI="true">

See also:

  • Unicode - How to get the characters right? - JSP/Servlet request

1 From Tomcat's documentation (emphasis mine):

This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitly set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false.


Please get rid of those scriptlets in your JSP. The request.setCharacterEncoding("UTF-8"); is called at the wrong moment. It would be too late whenever you've properly used a Servlet to process the request. You'd rather like to use a filter for this. The response.setCharacterEncoding("UTF-8"); part is already implicitly done by pageEncoding="UTF-8" in top of JSP.

I also strongly recommend to replace the old fashioned <%= request.getParameter("q") %> scriptlet by EL ${param.q}, or with JSTL XML escaping ${fn:escapeXml(param.q)} to prevent XSS attacks.

Solution 2:

you just need to uncomment below portion of code in conf/web.xml (Tomcat server web.xml) that filter all request and convert into UTF-8.

 <!-- A filter that sets character encoding that is used to decode -->
 <!-- parameters in a POST request -->
 <filter>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
 </filter>

  <!-- The mapping for the Set Character Encoding Filter -->
  <filter-mapping>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
  </filter-mapping>

that's it. work fine in tomcat