JSP Servlet JDBC MYSQL資料庫中文字元顯示為亂碼
阿新 • • 發佈:2019-02-15
這個過程中最終顯示為亂碼,是因為整個過程中字元編碼不統一導致。
要解決該問題,就是統一字元編碼。一般情況統一用UTF-8。
下面以UTF-8為例,解決中文字元顯示為亂碼
1.Input 文字編輯框一般接收GB18030編碼的字元
所以需要在Servlet獲取資料之前將Request資料重新用UTF-8進行編碼。
/* change the character encoding to utf-8. */
request.setCharacterEncoding("utf-8");
2.資料庫連結使用UTF-8格式
格式如下:
jdbc:mysql://XXXXXX:XXXX/XXX?characterEncoding=utf8
例子:
jdbc:mysql://localhost:3306/resource?characterEncoding=utf8
3.設定MYSQL字符集為UTF-8,在MySQL的初始化檔案my.ini中,設定如下配置項:
[client]
default-character-set=utf8
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
在MYSQL命令列下檢視如下:
mysql> show variables like 'character%';
+--------------------------+-------------------------------+
| Variable_name | Value |
+--------------------------+-------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | d:\work\mysql\share\charsets\ |
+--------------------------+-------------------------------+
8 rows in set, 1 warning (0.00 sec)
4.JSP頁面使用UTF-8 編碼
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<head>
<script>
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
要解決該問題,就是統一字元編碼。一般情況統一用UTF-8。
下面以UTF-8為例,解決中文字元顯示為亂碼
1.Input 文字編輯框一般接收GB18030編碼的字元
所以需要在Servlet獲取資料之前將Request資料重新用UTF-8進行編碼。
/* change the character encoding to utf-8. */
request.setCharacterEncoding("utf-8");
2.資料庫連結使用UTF-8格式
格式如下:
jdbc:mysql://XXXXXX:XXXX/XXX?characterEncoding=utf8
例子:
jdbc:mysql://localhost:3306/resource?characterEncoding=utf8
3.設定MYSQL字符集為UTF-8,在MySQL的初始化檔案my.ini中,設定如下配置項:
[client]
default-character-set=utf8
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
在MYSQL命令列下檢視如下:
mysql> show variables like 'character%';
+--------------------------+-------------------------------+
| Variable_name | Value |
+--------------------------+-------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | d:\work\mysql\share\charsets\ |
+--------------------------+-------------------------------+
8 rows in set, 1 warning (0.00 sec)
4.JSP頁面使用UTF-8 編碼
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<head>
<script>
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>