编码
<meta http-equiv="content-type" content="text/html;charset=utf-8"> http-equiv:用来模拟一些消息头 content-type消息头
告诉浏览器, 页面的编码格式
example : String str = URLEncoder.encode("小灰","utf-8"); 编码
//str:%E5%B0%8F%E7%81%B0
String str2 = URLDecoder.decode(str,"utf-8"); 解码
//小灰
解码 :
//告诉服务器,使用指定的编码格式进行解码。
request.setCharacterEncoding("utf-8");
生成一个消息头content-type,告诉浏览器 ,服务器返回的数据类型和编码格式。
告诉服务器,在输出时(out.println)时,使用指定的编码格式进行编码。
response.setContentType( "text/html;charset=utf-8");
当表单提交的时候,浏览器会按照打开该页面时的编码
格式对表单中的中文参数值进行编码。而服务器默认情况下,
会使用iso-8859-1这种编码格式进行解码。所以会出现乱码
问题。
解决办法:
方式一:
step1,要保证使用指定的编码格式打开页面。
比如,对于html文件,可以使用<meta http-equiv="content-type"
content="text/html;charset=utf-8">
step2,在服务器,使用
request.setCharacterEncoding("utf-8");
注意:
a,该方法必须要放在所有的request.getParameter方法的前面。
b, 只对post请求有效。
方式二:适用于get,post请求。
step1,要保证使用指定的编码格式打开页面。
step2, new String(str.getBytes("iso-8859-1"),
"utf-8");
(浏览器,服务器)----------------------------》》》》 数据库(乱码)
写入数据库,服务器编码好了,写入数据库
jdbc:mysql://localhost:3306/jd1301db?useUnicode=true&characterEncoding=utf8
数据库解码
打开mysql安装目录:C:\Program Files\MySQL\MySQL Server 5.5
打开文件my.ini配置文件,找到 default-character-set=latin1 并改为:
default-character-set=gbk,找到 character-set-server=latin1 并改为:
character-set-server=gbk,修改完之后保存。
最后:我的电脑右击 “管理”进入之后选择“服务和应用程序”下的“服务”
找到“mysql”之后右击选择“重新启动”。