spring+hibernate乱码

本文介绍了解决使用Spring和Hibernate框架时遇到的中文乱码问题。提供了两种有效的方法:一是更改MySQL数据库编码为gb2312,并调整applicationContext.xml配置;二是对数据进行编码转换。

今天用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());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值