1、使用带有缓冲区的字符流读文件产生的乱码
解决方案:让输入流读取文件时按照文件的编码格式来度
InputStream is=new FileInputStream("text.txt");
Reader reader=new InputStreamReader(is,"UTF-8");
BufferedReader br=new BufferedReader(reader);
2、post方式提交时产生的乱码
1>设置请求的编码方法:
request.setCharacterEncoding("utf-8");
2>设置响应的编码方法:
response.setCharacterEncoding("utf-8");
3、get方式提交时产生的乱码
1>治标:在读取数据时对数据进行编码
new String(username.getBytes("iso-8859-1"),"utf-8");
2>治本:通过配置tomacat\conf\server.xml文件
在<Connector port="8090" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" 添加:URIEncoding="utf-8" />
或者:添加useBodyEncodingForURI="true"
4、cookie填写中文用户名产生的乱码
4-1:先在提交时转码:Cookie cookie=new Cookie("user",URLEncoder.encode(username, "UTF-8"));
4-2:在注销时解码:String temp=URLDecoder.decode(cookies[i].getValue(),"UTF-8");