Search This Blog

Thursday, March 19, 2009

How to store UTF8 data into MYSQL (Java)

Well, i would like to share with yours 乱码解决方法 for Java / Mysql

There are few steps :

STEP 1.

Makesure every content delivery from your server tells the client (browser) the correct encoding to use.
example :

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

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





STEP 2.

Makesure configure your MYSQL DB Server to support Multilanguage and set the default charset and collate
Or during table creation set it !
example :

CREATE TABLE PROPERTY
(
ID BIGINT(10) NOT NULL auto_increment,
PROPERTY_NAME VARCHAR(200) NOT NULL,
DATECREATED DATETIME NOT NULL ,
CREATEDBY VARCHAR(50) NOT NULL,
DATEUPDATED DATETIME NOT NULL ,
UPDATEDBY VARCHAR(50) NOT NULL,
PRIMARY KEY (ID)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci
GO






STEP 3.

JDBC Connection
for MYSQL inorder to store and make sure the connection is using utf8 encoding you need to configure the JDBC URL to

jdbc:mysql://ServerName:3306/DBName?useUnicode=true&characterEncoding=UTF8




STEP 4. This step took me few days to research

Set the character encoding in your Java :
request.setCharacterEncoding("utf-8");
But sometime this didn't work...

Then you need to
configure this filter in your web.xml to be executed before every request:
<filter>
<filter-name>UTF8EncodingFilter</filter-name>
<filter-class>
com.vidasprint.common.UTF8EncodingFilter
</filter-class>

<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UTF8EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>