Linux mysql 中文乱码处理

来源:互联网 发布:男朋友 肌肉男 知乎 编辑:程序博客网 时间:2024/05/24 04:20

在项目中,通过tomcat上部署的web服务器,客户端通过http向服务器的mysql插入数据,但插入的中文会变成???这样的内容,原因有很多

1.服务器没有对request和response进行编码处理,这点好解决,可以通过设置字符集来处理

/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse *      response) */protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8"); //这句话的意思,是让浏览器用utf8来解析返回的数据          response.setHeader("Content-type", "text/html;charset=UTF-8");  service(request, response);}

2.如果这样仍然会有中文乱码,可以尝试在1的基础上添加filter处理

@WebFilter("/CharsetFilter")public class CharsetFilter implements Filter {    /**     * Default constructor.      */    public CharsetFilter() {          }/** * @see Filter#destroy() */public void destroy() {}/** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8"); chain.doFilter(request, response);}/** * @see Filter#init(FilterConfig) */public void init(FilterConfig fConfig) throws ServletException {}}
3.如果设置了filter仍然解决不了中文乱码,可能就是mysql服务器出现了问题,可以通过查询编码设置来查看是否有问题

这个是设置好的值,如果有中文乱码问题,一些value的值应该是latin或者是其他的编码表

4.彻底的解决这个问题,本人通过xftp软件对linux的文件进行处理,方便.

找到/etc/my.cnf,替换为一下内容

[mysql]no-auto-rehashdefault-character-set=utf8[mysqld]port = 3306datadir=/var/lib/mysqlsocket=/var/lib/mysql/mysql.sock# Disabling symbolic-links is recommended to prevent assorted security riskssymbolic-links=0default-character-set = utf8character-set-server = utf8# Settings user and group are ignored when systemd is used (fedora >= 15).# If you need to run mysqld under a different user or group,# customize your systemd unit file for mysqld according to the# instructions in http://fedoraproject.org/wiki/Systemduser=mysql# Semisynchronous Replication# http://dev.mysql.com/doc/refman/5.5/en/replication-semisync.html# uncomment next line on MASTER;plugin-load=rpl_semi_sync_master=semisync_master.so# uncomment next line on SLAVE;plugin-load=rpl_semi_sync_slave=semisync_slave.so# Others options for Semisynchronous Replication;rpl_semi_sync_master_enabled=1;rpl_semi_sync_master_timeout=10;rpl_semi_sync_slave_enabled=1# http://dev.mysql.com/doc/refman/5.5/en/performance-schema.html;performance_schema[mysqld_safe]log-error=/var/log/mysqld.logpid-file=/var/run/mysqld/mysqld.piddefault-character-set = utf8[mysql.server]default-character-set = utf8[client]port = 3306default-character-set = utf8socket = /var/lib/mysql/mysql.sock
5.重启mysql服务即可

service mysql stop service mysql start

或者直接

service mysql restart