java中解决request中文乱码问题

request乱码问题(当我们提交的数据中含有中文信息时),分两种情况:

  • 通过post方式提交数据给Servlet

       Servlet服务端部分代码:

       

public void doPost(httpServletRequest request, httpServletResponse response)

                         throws ServletException, IOException{

             //在获取用户表单信息之前把request的码表设置成UTF-8,

             //如果没这句的话,如果提交中文信息的时候,会乱码。

             request.setCharacterEncoding("UTF-8");             

             String value = request.getParameter("username"); //从request中获取客户端提交过来的信息

             System.out.println(value);

       }

 

  • 通过get方式提交数据给Servlet (要手动处理)

       Servlet服务端部分代码:

      

 public void doGet(httpServletRequest request, httpServletResponse response)

                         throws ServletException, IOException{

             //从request中获取客户端提交过来的中文信息,获取到乱码  

             String value = request.getParameter("username"); 

             //拿到乱码反向查找 iso-8859-1 码表,获取原始数据,

             //在构造一个字符串让它去查找UTF-8 码表,已得到正常数据

             value1 = new String (value.getBytes("iso-8859-1"), "UTF-8") ; 

             System.out.println(value);          

                   }

 

  • 用超链接提交表单信息(通过 get 方式提交,需调用到doGet方法)

       

<a href="/Servlet/test?username=江西">登录<a/>

 总结:

   通过get提交表单信息有两种: 

     1.通过form表单的 method 设置 get方法提交(即method="get") 默认也是 get

       通过get方法提交到 Servlet程序中, 首先是得到表单的信息,但是乱码,

       然后还得手动去设置编码方式

       即 value1 = new String (value.getBytes("iso-8859-1"), "UTF-8")

 

     2.通过超链接提交

 

   通过post提交表单:

       在form表单的 method 设置 post方法提交(即method="post") ,

       通过post方法提交到 Servlet程序中,request 要在得到表单信息之前 设置编码方式

       即 request.setCharacterEncoding("UTF-8");

 

get: 通过get提交表单的信息,地址栏上可以看到,安全性不好

post:通过post提交表单的信息,地址栏上看不到表单的信息,

 

出现这种机制的原因:

      在于http协议上,通过get提交的信息加在url后面,所以能看到;

      通过post提交的信息是在请求体上的,也就是你敲了两次回车后,发送的信息,所以看不到

 

如果以上方法没有效果,可以尝试使用java.net.URLDecoder.decode(URIString, "UTF-8")方法:

encodeURI和decodeURI是成对来使用的,因为浏览器的地址栏有中文字符的话,可以会出现不可预期的错误,所以可以encodeURI把非英文字符转化为英文编码,decodeURI可以用来把字符还原回来。encodeURI方法不会对下列字符进行编码:":"、"/"、";" 和 "?",encodeURIComponent方法可以对这些字符进行编码。 
decodeURI()方法相当于java.net.URLDecoder.decode(URIString, "UTF-8"); 
encodeURI()方法相当于java.net.URLEncoder.encode(URIString, "UTF-8"); 

二、例子 

<script type="text/javascript"> 
var uriStr = "http://www.baidu.com?name=张三&num=001 zs"; 
var uriec = encodeURI(uriStr); 
document.write("编码后的" + uriec); 
var uridc = decodeURI(uriec); 
document.write("解码后的" + uridc); 
</script> 

编码后的http://www.baidu.com?name=%E5%BC%A0%E4%B8%89&num=001%20zs 
解码后的http://www.baidu.com?name=张三&num=001 zs

posted @ 2016-08-23 17:11  Franson  阅读(1989)  评论(0编辑  收藏  举报