目录
MySQL乱码问题
1、前台页面
JSP、HTML页面头部设置字符编码为UTF-8。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> |
2、控制器/过滤器(filter)
(1)servlet设置页面请求和回应的编码:
request.setCharacterEncoding("utf-8"); [一般用于post请求方式]
|
(2)如果是struts2
struts.xml中添加如下语句: <constant name="struts.i18n.encoding" value="utf-8" /> |
(3)如果使用了spring框架
web.xml配置中,设置初始化参数 <filter>
public class YkFilter implements Filter{ //其他代码未全部写出,这里只写出和编码相关的语句 private String encoding = null;//定义表示编码方式的变量 @Override
@Override ............. }
} |
3、数据库及表格编码
第一:保证数据库的编码方式为UTF-8; 第二:保证数据表的编码方式为UTF-8; 第三:使用jdbc连接数据库时,在URL中添加useUnicode参数(useUnicode=true表示使用Unicode字符集)和characterEncoding参数(characterEncoding=utf8,当useUnicode设置为true时,指定字符编码) 如:jdbc:mysql://localhost:3306/database_name?useUnicode=true&characterEncoding=utf8" 数据库及数据表的编码格式查看及修改请查看:MySQL相关命令 |
4、字符流编码
String string = request.getParametes('sname'); //把得到的值转换为原始编码,再转换为UTF-8编码 string=new String(string.getBytes("iso8859-1"),"UTF-8"); [一般用于get请求] |
5、Tomcat编码
想通过get请求带中文数据也不会出现乱码,还需要编辑Tomcat的编码
在server.xml文件中,在端口号8080后添加编码格式 URIEncoding=”utf-8”
<Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" UTFEncoding=”utf-8” />
|