服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

spring+hibernate乱码解决方案


  今天用spring+hibernate进行中文插入时出现乱码问题,通过查资料和自己反复测试终于解决了.

  总结了两种方法:

  1、使用gb2312编码,变更mysql的数据库编码字符集。cmd模式下用mysql --default-character-set=gb2312 -u root -p进入,然后再每个建表语句后增加default character set gb2312;

  重新建立数据表。

  值得注意的地方是:applicationcontext.xml中的数据库连接必须设置为<property name="url"><value>jdbc:mysql://localhost/struts?useunicode=true&characterencoding=gb2312</value></property>,这样插入的才是正常的中文,否则就是乱码。

  2、在进行数据保存之前进行gb2312到iso8859-1编码的转换,applicationcontext.xml中的数据库连接必须设置为<property name="url"><value>jdbc:mysql://localhost/struts</value></property>,这样插入的才是正常的中文,否则就是乱码。

  它们相同的地方是在用jsp进行中文内容填加时,都要进行gb2312到iso8859-1编码的转换:

string name;
name=trans(request.getparameter("name"));

string trans(string chi)
{
 string result = null;
 byte temp [];
 try
 {
  temp=chi.getbytes("iso-8859-1");
  result = new string(temp);
 }
 catch(java.io.unsupportedencodingexception e)
 {
  system.out.println (e.tostring());
 }
 return result;
}
string trans(object chi)
{
 return trans(chi.tostring());
}

扫描关注微信公众号