Blueherb In solitude, where we are least alone

JSP+MySQL中文乱码

问题: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")

 

posted @ 2014-08-26 17:05  Blueherb  阅读(692)  评论(0编辑  收藏  举报