標籤:style blog color os java io 檔案 ar 資料
問題:JSP頁面傳輸到MySQL資料庫時,中文為亂碼(資料庫中儲存亂碼)。
解決辦法:
1、將所有的涉及到編碼的都設定為 utf8(utf-8)。
設定資料庫編碼:命令列執行:mysql> show variables like ‘character%‘; 可以查看是否為utf8
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 | latin1 || character_set_system | utf8 || character_sets_dir | D:\Program Files\mysql-5.6.20-winx64\share\charsets\ |+--------------------------+------------------------------------------------------+
character_set_server項不知道如何設定,不過不影響。修改資料庫編碼執行命令: mysql> alter database db_name character set utf8;
修改其他編碼: mysql> set names ‘utf8‘;
設定JSP頁面編碼:在頁面頂部添加
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
修改資料庫連接DriverManager.getConnection(url, usr, pwd)的url:
String url = "jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8";
2、post傳輸方式
在發送頁面和接收頁面頂部都添加以下代碼:
1 <% request.setCharacterEncoding("UTF-8"); 2 response.setCharacterEncoding("UTF-8"); 3 response.setContentType("text/html; charset=utf-8");4 %>
(關於get方式,即在地址欄參數不知道如何修改。似乎需要修改Tomcat的server.xml檔案中URIEncoding="UTF-8")
JSP+MySQL中文亂碼問題