1. java编码类型基础
System.out.println(URLEncoder.encode("齐", "utf-8")); //%E9%BD%90(3字节)
System.out.println(URLEncoder.encode("齐", "GB2312")); //%C6%EB (2字节)
System.out.println(URLEncoder.encode("齐", "ISO-8859-1")); //%3F (1字节 这是由于汉字在ISO-8859-1字符集中不存在,返回的是?在ISO-8859-1下的编码)
我们的url用什么编码,必须用什么解码,否则乱码。
2. tomcat 默认编码
当我们在实用tomcat 做容器时,他的默认编码格式为(ISO-8859-1),他是不认识中文的。可以通过
设置tomcat 编码格式
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="gbk"/> 注意: tomcat只能设置Get方法的请求编码,Post请求需要通过req.setCharacterEncoding("utf-8")或过滤器解决。
3. Url如何传中文
页面用 encodeURIComponent()两次编码,例如
function testencode(){
var encodeVal = encodeURIComponent("两次编码");
window.location.href="HttpsJosnServlet?name="+encodeVal;
}
servlet解码,
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = (req.getParameter("name") == null) ? null : req.getParameter("name");
String nema = URLDecoder.decode(name, "utf-8"); //解码一次
} 注意: js函数会自动解码一次 ,所有要编码3次或者用onclick替代。