发生中文乱码一般有以下几种情况
1.form提交
1)post提交
解决办法:在服务器端设置浏览器端的编码方式。
request.setCharacterEncoding("utf-8");
2)get提交
写一个工具类:
public class EncodingTools {
public static String getNewString(String str) {
String newString="";
try {
newString=new String(str.getBytes("iso-8859-1"),"utf-8");
} catch (Exception e) {
e.printStackTrace();
// 把iso-8859-1 转换成 utf-8
}
return newString;
}
}
2.超链接
<a href=”http://www.sohu.com?name=姓名”>测试</a>
该方法和get处理方法一样.
response.sendRedirect(“servlet地址?username=姓名”);
4.返回浏览器显示乱码
在服务端是中文,在response的时候,也要考虑浏览器显示是否正确,一般我们通过
response.setContentType(“text/html;charset=utf-8”);
5.下载提示框中文乱码
当我们下载文件的时候,可能提示框是中文乱码 ,可以这样解决:
String temp=java.net.URLEncoder.encode("传奇.mp3","utf-8");
response.setHeader("Content-Disposition","attachment; filename="+temp);
6.版本低导致的乱码
特别说明,如果你的浏览器是 ie6 或以下版本,则我们的 2 和 3情况依然可能会出现乱码(当中文是奇数的时候)
解决方法和上面的情况差不多 :
String temp=java.net.URLEncoder.encode("你好吗.jpg", "utf-8");
<a href=”http://www.sohu.com?name=”+ temp >测试</a>
response.sendRedirect(“servlet地址?username=”+temp);