发生中文乱码有以下几种情况:
1、表单form
post提交
因为服务器接受的时候用iso-8859-1方式接受的,所以在服务器端设置成浏览器端的编码方式。
复制代码
1
2解决方法: request.setCharacterEncoding("utf-8"); //是http请求体里面的内容
get提交
参数放在请求行,不在请求体里面.所以要进行转码处理
写一个工具类:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.zm.util; 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) { e.printStackTrace(); // 把iso-8859-1 转换成 utf-8 } return newString; } }
2、超链接
复制代码
1
2<a href=”http://www.sohu.com?name=张三”>测试</a>
该方法和get提交处理方法一样.
3、sendRedirect() 发生乱码
复制代码
1
2response.sendRedirect(“servlet地址?username=张三”); //相当于重新发送请求,更改了编码方式
版本低导致的乱码
特别说明,如果你的浏览器是 ie6 或以下版本,则我们的 ② 和 ③中情况会出现乱码(当中文是奇数的时候)
解决方法是 :(需要对发送的中文进行URLEncoding)
①发送方(MyForm1.java):
复制代码
1
2
3String info=java.net.URLEncoder.encode(“图片.jpg", "utf-8"); out.println("<a href=”/EncodingPro/GetInfoServlet?username=”+ info+"" >测试</a>
②接收方(GetInfo.java):
复制代码
1
2String username=new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
如果GetInfo还要继续往下传递,即sendRedirect,则:
复制代码
1
2
3String info=java.net.URLEncoder.encode(username, "utf-8"); response.sendRedirect(“/Encoding/Welcome?username=”+info);
③第三个文件(Welcome.java):
复制代码
1
2String username=new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
说明: 我们应当尽量使用post 方式提交;
4、返回浏览器显示乱码
在服务端是中文,在response的时候,也要考虑浏览器显示是否正确,一般我们通过
复制代码
1
2response.setContentType(“text/html;charset=utf-8”); //ok
5、下载提示框中文乱码
补充一个知识点: 当我们下载具有中文名的文件的时候,可能提示框是中文乱码
解决办法:
复制代码
1
2
3String temp=java.net.URLEncoder.encode("传奇.mp3","utf-8"); response.setHeader("Content-Disposition","attachment; filename="+temp);
6、cookie保存中文乱码
复制代码
1
2
3
4
5
6
7
8
9
10//创建中文cookie Cookie cookie2=new Cookie(URLEncoder.encode("籍贯","utf-8"),URLEncoder.encode("北京","utf-8")); //读取该web应用的所有cookie[可能带中文] Cookie[] cookies=request.getCookies(); for(int i=0;i<cookies.length;i++){ System.out.println("Cookie:name="+URLDecoder.decode(cookies[i].getName(),"utf-8") +",value="+URLDecoder.decode(cookies[i].getValue(),"utf-8")); }
7、js提交中文参数乱码
//js文件【注意:js文件本身应使用utf-8编码】
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14function toSubmit(){ var url="/TestHttp/ServletDemo9?name=张三"; url=encodeURI(encodeURI(url)); //注意,须两次使用encodeURI()方法 window.location.href=url; } //服务器端 String name=request.getParameter("name"); name=URLDecoder.decode(name, "utf-8"); //URL解码 System.out.println("name="+name);
最后
以上就是健壮歌曲最近收集整理的关于中文乱码解决的全部内容,更多相关中文乱码解决内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复