servlet请求乱码问题的一些处理

 1、什么是url编码?
 浏览器对链接中的特殊字符(非ascii字符以及一些
 标点符号等)会进行编码处理。中文就需要编码。
 2、链接当中包含了中文参数,浏览器会对中文
 参数进行编码,编码依据打开该页面时的编码。
  如果请求发送方式是get方式,不能够使用
  request.setCharacterEncoding()!
  解决方式一:
   new String(str.getBytes("iso8859-1"),"编码");
   注意,编码要看浏览器打开页面时的编码。
  解决方式二:
   在tomcat conf\server.xml找到
   <Connector port="8080",在末尾添加
   URIEncoding="utf-8",其作用是,告诉
   服务器,对于get请求,采用utf-8解码。
 3、链接地址包含中文,浏览器一定会以utf-8编码。
 4、对于ajax
  (1)
  如果是get请求,ie会按gb2312编码,而
  firefox会按utf-8编码。
  可以使用encodeURI()对请求地址进行编码处理。
  该函数以utf-8来编码。
  step1 : 使用encodeURI()对url进行编码处理。
  即xhr.open("get",encodeURI("some.do?name=张三"),true);
  step2:在tomcat conf\server.xml找到
   <Connector port="8080",在末尾添加
   URIEncoding="utf-8"或者
   String str = request.getParameter("name");
   new String(str.getBytes("iso8859-1"),"utf-8");
  (2)如果是post请求,没有编码问题。

 1 <%@ page  import="java.net.*" contentType="text/html; charset=gbk"
 2     pageEncoding="gbk"%>
 3 <html>
 4 <head>
 5     <title>Insert title here</title>
 6 </head>
 7 <body style="font-size:30pt;">
 8     <a href="some?name=<%=URLEncoder.encode("张三","utf-8")%>">invoke some</a>
 9 </body>
10 </html>
 1 package web;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class SomeServlet extends HttpServlet {
12 
13     public void service(HttpServletRequest request, HttpServletResponse response)
14             throws ServletException, IOException {
15         String name = request.getParameter("name");
16         name = new String(name.getBytes("iso8859-1"),
17                 "utf-8");
18         System.out.println("name:" + name);
19         
20     }
21 
22 }

 

1 public static void main(String[] args) throws UnsupportedEncodingException {
2         // TODO Auto-generated method stub
3         String str1 = URLEncoder.encode("张三","gbk");
4         System.out.println("str1:" + str1);
5         String str2 = URLDecoder.decode("%E5%BC%A0%E4%B8%89","utf-8");
6         System.out.println("str2:" + str2);
7     }

 

posted @ 2012-08-16 13:52  欢歌911  阅读(404)  评论(0编辑  收藏  举报