发生中文乱码通常出如今下面三种状况中:html
①表单form中java
由于表单在提交请求的数据的时候也能够带参数。好比:浏览器
<from action='/UsersManager3/UserClServlet?type=update' method='post'>安全
(1)post服务器
解决方法:request.setCharacterEncoding("utf-8");// gbk gb2312 big5函数
(2)get工具
写一个工具类post
package com.hsp.utils; public class MyTools { public static String getNewString(String str) { String newString = ""; try { newString = new String(str.getBytes("iso-8859-1"), "utf-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return newString; } }
②超连接测试
<a href="http://www.sohu.com?name=函数">测试</a>spa
该方法和get处理方法同样。
③sendRedirect()发生乱码
response.sendRedirect("servlet 地址?username=顺平"); //此时客户端向服务器端发送了一个请求。
说明一:
特别说明,若是你的浏览器是ie6或如下版本,且中文是奇数的时候 ,则咱们的②和③中的状况依然会出现乱码。
解决方法是:
第二种状况的解决方法:
String info = java.net.URLEncoder.encode("你好吗.jpg", "utf-8");
<a href="http://http://www.sohu.com?name=" + info>测试</a>
第三种状况的解决方法:
String info = java.net.URLEncoder.encode("你好吗.jpg", "utf-8");
response.sendRedirect("servlet地址?username=" + info);
说明二:
咱们应当尽可能使用post方式提交。由于其安全,提交的数据量也更大。
说明三:
在服务器端是中文,在response的时候,也要考虑浏览器显示是否正确,通常咱们经过response.setContentType("text/html;charset=utf-8");设置回送的中文的格式。
另外在这个知识点上补充一个知识点:当咱们下载文件的时候,可能提示框是中文乱码,解决方法:
String temp = java.net.URLEncoder.encode("传奇.mp3", "utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + temp);