解答:将本地项目存放在云服务器linux下,存入数据,数据库mysql下是乱码。问题存在的地方包括:mysql的字符编码、框架存在乱码包括struts2层及hibernate层。
1. mysql字符编码若不是urf-8,则需要改为utf-8。在新建mysql数据库时则需要设置编码格式为utf-8
2. Struts2层没有设置为utf-8,
l 可通过在struts.xml中添加 <constant name="struts.il8n.encoding" value="UTF-8" />但是效果不是很好。
l 还可以在实体类的set方法中将所有的string类型中添加如下
public void setId(String id) {
try {
id=new String(id.getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
this.id = id;}
然后将request和response也设置为utf-8
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("text/html;charset=UTF-8");
注意:不可同时多次为utf-8,因为转多次也会导致乱码
3. hibernate层设置为utf-8
在hibernate.cfg.xml中:
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/lvyou_db?useUnicode=true&characterEncoding=utf8
若还存在乱码,可查看tomcat版本是否存在不一致的情况。本人修改了很久的乱码问题,都没找到解决办法,后来将云服务器上的tomcat版本改为和本地的tomcat一致后就不存在乱码了。