在计算机中,只有二进制的数据,不同字符对应二进制的规则,就是字符的编码。
常用字符集:Ascii码;iso8859-1码;gb2312和gbk;unicode;utf-8;
出现乱码的解决方案:
1、 以post方法提交的数据中有中文字符, 可以在获取请求参数值之前,调用request.setCharacterEncoding(“UTF-8”),指定请求正文使用的字符编码是UTF-8;
2、在向浏览器发送数据之前调用 response.setHeader("Content-Type", "text/html;charset=UTF-8");这是最好的一种解决方法
3、用OutputStream输出数字时出现乱码解决:response.getOutputStream().write((97+"").getBytes()); //97任意数字
4、response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
response.getOutputStream().write("中国".getBytes("UTF-8"))。
当下载以中文名称的文件时出现乱码的解决方案:
设置消息头
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
//URLEncoder.encode(String,String)方法是:使用指定的编码机制将字符串转换为
application/x-www-form-urlencoded
格式。