日期:2014-05-20  浏览次数:20614 次

URLDecoder 和URLEncoder 有什么区别
a.jsp代码:

<%
Cookie cookie = new Cookie("name", URLEncoder.encode("乱码", "utf-8"));
response.addCookie(cookie);
// response.sendRedirect("a.jsp");
request.getRequestDispatcher("a.jsp").forward(request, response);
%>

b.jsp页面代码

<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("name")) {
out.println(URLDecoder.decode(cookies[i].getValue(),
"utf-8")
+ " " + cookies[i].getName());
}
}
}
%>

为什么 添加cookie的是很 用 URLEncoder.encode("乱码", "utf-8")这个类 读取cookie的值时用URLDecoder他 如果调换位置 或者都用同一个类 就还是乱码 请问高手 这两个类有什么区别

------解决方案--------------------
URLEncoder和URLDecoder的关系,就像是加密和解密的关系。

URLEncoder是转码,URLDecoder是解码。
中文在一些情况下是乱码,需要转码。此时需要使用URLEncoder转码,一般是转成%AB%FG%UF(这个只是例子)这样的形式。
而读取的时候需要从%AB%FG%UF这种形式解码成正常的中文。此时使用URLDecoder。