Programming     Travel Logs     Life Is Good     Surfing Online     About Me
Fortunes require leverage. Business leverage comes from capital, people, and products with no marginal cost of replication (code and media).
-Naval Ravikant
2018-06-16 22:29:30

Copy this link when reproducing:
http://www.casperlee.com/en/y/blog/182

When trying to commit Chinese data into the database in my application, I encountered a few errors. It turns out that I need to do a few modifications for my application, so that it can support Chinese characters.

/Images/20170923/01.jpg

/Images/20170923/02.jpg

/Images/20170923/03.jpg

/Images/20170923/04.jpg

/Images/20170923/05.jpg

/Images/20170923/06.jpg

1. Modifications for the project in Eclipse.

    Right click on the project, select "Properties" from the popped menu, a dialog popped up:

/Images/20170923/101.jpg

    Make sure the "Text file encoding" is set to "UTF-8".

2. Modifications for Tomcat server.

    I. Open the configuration file "[Tomcat Install Path]\conf\server.xml", find the Connector for port 8080, add attribute "URIEncoding" and "useBodyEncodingForURI":

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" 
               URIEncoding="UTF-8" 
               useBodyEncodingForURI="true"/>

    II. Eclipse also created a local server for Tomcat, so we need to modify another "server.xml" too. It is located in "[Java Working Folder]\Servers\Tomcat v9.0 Server at localhost-config\server.xml".

3. Modifications for Spring.

    Open the configuration file "WebContent\WEB-INF\web.xml", and put the following lines in:

<filter>  
    <filter-name>characterEncodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
      <param-name>encoding</param-name>  
      <param-value>UTF-8</param-value>  
    </init-param>  
    <init-param>  
      <param-name>forceEncoding</param-name>  
      <param-value>true</param-value>  
    </init-param>  
  </filter>  
  <filter-mapping>  
    <filter-name>characterEncodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
  </filter-mapping>

4. Modifications for data source.

Open the configuration file "WebContent\WEB-INF\config\springmvc-config.xml", and add the configuration for character encoding:

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
        destroy-method="close">
      ...
      <property name="url" value="jdbc:mysql://localhost:3306/DayDB?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8" />
	  ...
    </bean>

5. Modifications for JSP files.

    Put this line into each .jsp file:

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

6. Done!