spring开发时所遇的乱码问题

前几天在测试时发现从前端访问你数据库出现乱码。经过分析应该是前端和后端,后端和数据库之间进行数据交换时编码不一致导致的。


  1. 首先,前端通过浏览器向后端传输数据有两种途径:

    • 一是通过地址栏,这时候采用的是系统默认编码;
    • 二是通过浏览器控制台,通过js向后台传输数据时默认采用utf-8编码

    我用的是spring+tomcat,所以要配置spring解析URL时采用utf-8编码。tomcat默认采用ISO-8859-1编码解析uri,因此具体的话应该是配置:
    tomcat -> server.xml -> Connector -> URIEncoding。

  2. 后端向前端传输数据时,一般来说,response里面写入的时编码后的bytes,传到前端后,前端后再用相应的编码解码,就可以了。

  3. 后端与数据库交互时,我们知道数据库内部设置后很多编码。以mysql为例

    Variable_nameValue
    character_set_clientlatin1
    character_set_connectionlatin1
    character_set_databaselatin1
    character_set_resultslatin1
    character_set_serverlatin1
    character_set_systemutf8
    character_sets_dir/usr/share/mysql/charsets/

    这么多编码简直让人头大。不过在这里有三个编码是动态的,有连接数据库的客户端决定。这三个编码就是

    character_set_client
    character_set_connection
    character_set_results

    这三个编码的作用如何,文档摘录如下:

    • What character set is the statement in when it leaves the client?
      The server takes the character_set_client system variable to be the character set in which statements are sent by the client.
    • What character set should the server translate a statement to after receiving it?
      For this, the server uses the character_set_connection and collation_connection system variables. It converts statements sent by the client from character_set_client to character_set_connection (except for string literals that have an introducer such as _latin1 or _utf8). collation_connection is important for comparisons of literal strings. For comparisons of strings with column values, collation_connection does not matter because columns have their own collation, which has a higher collation precedence.
    • What character set should the server translate to before shipping result sets or error messages back to the client?
      The character_set_results system variable indicates the character set in which the server returns query results to the client. This includes result data such as column values, and result metadata such as column names and error messages.
      Clients can fine-tune the settings for these variables, or depend on the defaults (in which case, you can skip the rest of this section). If you do not use the defaults, you must change the character settings for each connection to the server.

大概是说:

  • mysql认为,客户端传过来的statements是以character_set_client编码的;
  • mysql用character_set_client对statements解码,然后用character_set_connection对其编码。
  • 执行statements得到的结果,mysql会将其以character_set_results编码传给客户端。

sping通过jdbc链接mysql,但是具体采用的编码方式是什么?一味的采用默认值很容易出现乱码。因此,在配置jdbc的时候要显式地配置编码方式。具体就是:
在jdbc.url后添加useUnicode=true&characterEncoding=UTF-8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值