Fix Tomcat Garbled Text: UTF-8 Guide

There are several ways to solve the encoding problem in Tomcat:

  1. Set the URIEncoding attribute to UTF-8 in the Connector tag in the server.xml configuration file of Tomcat.
  2. Use UTF-8 encoding for the URI in the Connector configuration.
  3. Set character encoding filters for requests and responses in the web.xml configuration file of Tomcat.
  4. Set up a filter called encodingFilter that uses the class org.apache.catalina.filters.SetCharacterEncodingFilter, with the encoding parameter set to UTF-8 and the ignore parameter set to true. The filter is mapped to all URL patterns.
  5. Add the following code to the head section of the JSP page to set the character encoding of the page to UTF-8.
  6. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

    Rewrite it in English as follows:

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

  7. In Java code, use UTF-8 encoding to read and write data. For example, set the character encoding for requests and responses to UTF-8.
  8. Set the character encoding for the request and response to “UTF-8”.
  9. When using a database, make sure that the character encoding of the database is also set to UTF-8. You can specify the character encoding when connecting to the database.
  10. The database connection string for my database on localhost is jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8.

Here are some common solutions to fix Tomcat encoding issues, choose the best method that fits your specific situation.

bannerAds