博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助
隐藏
yexin218.cublog.cn
Aja与servlet中文传输问题
最近在写一个ajax音乐搜索的引擎。所以一直都被中文问题传输捆住了,弄了好半天,才有点眉目。却急切跟大家分享。
音乐搜索的用户操作界面:
 

<%@ page contentType="text/html;charset=GB2312" language="java" %>
<%@page pageEncoding="GB2312"%>
<head>
    <META http-equiv=Content-Type content="text/html; charset=GB2312">
</head>
    <script type="text/javascript" src="js/baidusongs.js" ></script>
    <script type="text/javascript" src="js/http_request.js"></script>
    <title>Bai Du Songs</title>
    <style type="text/css">
。。
<span class="STYLE2">Name of Song(歌名):</span>
  <input name=
        "song_name" type="text" id="song" value="You" size="20" maxlength="20" />
</p>
<p>
  <span class="STYLE2">Name of Singer(歌手):</span>
  <input type="text" id="singer" name=
        "singer_value" size="20" maxlength="20" />
</p>
<p>
<!--<span id="addr_song"></span><br/>
<span id="addr_word"></span>-->

<div id = "addr_song"></div>
<div id = "addr_word"></div>
  
</p>
<p>
<button type="button" class="STYLE2" id="songsearch">Search</button>

我把整个页面的编码设置成:gb2312, 网上有的资料说是统一用utf8格式,我自己试了一下,如果编码是utf8,那么需要把该文件存储成编码为utf-8的,否则也会出现页面乱码(错了吗?)。用户输入的参数由js来处理:

 

window.onload = function(){
     document.getElementById("songsearch").onclick=function(){
        var _song= document.getElementById("song");
        var _singer=document.getElementById("singer");
        if(_song.value){
          getSong(_song.value,_singer.value);
        }
  
     };
     //defualt value

     //getSong("等一分钟","");

};
function getSong(song,singer){
     if(song == null){
         document.getElementById("song").value="";
         //return ;

     }else{
     var url = "http://localhost:8080/baidusongs/songsearch?song="+encodeURI(song)+"&singer="+encodeURI(singer)+"&timeStamp="+ new Date().getTime();
    // var url = "http://localhost:8080/baidusongs/songsearch?song="+escape(song)+"&singer="+escape(singer)+"&timeStamp="+ new Date().getTime();

     httpRequest("GET",url,true,handleResponse);
     }
}

 

查了很多资料,有的说是把song="+encodeURI(song)+"&singer="+encodeURI(singer)写成escape(song)这种形式的,我试了一下,发现这样根本无法把参数传送到servlet.不知道他们怎么弄得。没有搞明白......

数据传送到servlet,又遇到了编码的问题:

 

protected void doGet(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) throws ServletException,
            IOException {
        httpServletResponse.setContentType("text/xml;charset=GB2312");
        httpServletRequest.setCharacterEncoding("GB2312");
        //httpServletResponse.setCharacterEncoding("UTF-8");

        //String song = httpServletRequest.getParameter("song");

        //String song= new String(httpServletRequest.getParameter("song").getBytes("ISO-8859-1"), "GB2312");

        //String singer =new String(httpServletRequest.getParameter("singer").getBytes("ISO-8859-1"), "GB2312");

        String song = httpServletRequest.getParameter("song");
        String singer = httpServletRequest.getParameter("singer");
        System.out.println("Song name:"+song +"\n singer "+singer+"\n");
        String resp = null;
        if (!song.equals("")) {
            URL songUrl = new URL(baiduUrl+song+"$$"+singer+"$$$$");
            HttpURLConnection songCon = (HttpURLConnection) songUrl
                    .openConnection();
            songCon.setRequestMethod("GET");
            songCon.setDoInput(true);
            songCon.connect();
  
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    songCon.getInputStream()));
            StringBuffer buf = new StringBuffer("");
            String inputLine;
            while ((ininputLine = in.readLine( )) != null) {
                buf.append(inputLine); }
            in.close( );
            resp = buf.toString( );
            System.out.println("#######################");
            System.out.println(resp);
            System.out.println("#######################\n");
          try{
              getAddress(resp);
              resp="<songaddr>"+this.getSongAddr()+"</songaddr><wordaddr>"+this.getWordAddr()+"</wordaddr>";
            //System.out.println("_________________"+resp+"\n");

                
          }catch(ParserConfigurationException e){
              e.printStackTrace();
          }
  
        }else{
             resp="<error />";
  
        }
        //httpServletResponse.setContentType("text/xml; charset=UTF-8");

        //Convey to the user agent or browser that it should

        //not cache the responses

       // httpServletResponse.setHeader("Cache-Control", "no-cache");

       // httpServletResponse.getWriter( ).write(resp);

  
        httpServletResponse.setContentType("text/xml; charset=GB2312");
        String content = "<?xml version=\"1.0\" encoding=\"GB2312\"?>"+"<baidu><address><song_addr>"+getRealSongAddr(this.getSongAddr(),this.getSongName())+"</song_addr>"+"<word_addr>"+getRealWordAddr(this.getWordAddr())+"</word_addr></address></baidu>";
        System.out.println("*******************\n");
        System.out.println(content);
        System.out.println("*******************\n");
        httpServletResponse.getWriter( ).write(content);
  
    }


 httpServletRequest.setCharacterEncoding("GB2312");
 String song = httpServletRequest.getParameter("song"); 
 String singer = httpServletRequest.getParameter("singer");

我记得以前如果参数从jsp传到servlet这样写就可以了,不会乱码,可是这次就不行了。

后来我把它改成:

String song= new String(httpServletRequest.getParameter("song").getBytes("ISO-8859-1"), "GB2312");    

String singer =new String(httpServletRequest.getParameter("singer").getBytes("ISO-8859-1"), "GB2312");

可是发现还是出现乱码,已经作转换了可是还是不行。我不知道具体的原因,难道是从页面送过来的参数不是gb2312编码的,也许是utf8的。

那就改成

String song= new String(httpServletRequest.getParameter("song").getBytes("ISO-8859-1"), "UTF8");    

String singer =new String(httpServletRequest.getParameter("singer").getBytes("ISO-8859-1"), "UTF8");

没有想到这样就不会出现了乱码。

我在网上找到这样的例子:

http://hi.baidu.com/zbzb/blog/item/3afeafd37644ce34960a1658.html

 

servlet
        response.setContentType("text/xml");

        //这个一定要设置,这里的设置应该跟HTML中的一样,但是我在这里
        //用了 uft-8, 结果也是一样。
        response.setCharacterEncoding("GB2312");
      
        //当用POST方法时,一定要设置成utf-8,否则乱码
        String firstName = new String(request.getParameter("firstName").getBytes("ISO-8859-1"), "utf-8");

        //当用GET方法时,要设置成GB2312,否则乱码。
        String lastName = new String(request.getParameter("lastName").getBytes("ISO-8859-1"), "GB2312");

我觉得,我的参数使用get方法传送的,可是gb2312确实乱码的,反utf-8显示正常。不知道这是怎么回事?有待细细考究。

发表于: 2007-08-18,修改于: 2007-08-18 15:49,已浏览2096次,有评论5条 推荐 投诉
网友: Daming 时间:2007-08-29 10:44:59 IP地址:220.201.36.★
encodeURI -> UTF8编码格式

网友: yexin218 时间:2007-08-29 10:49:39 IP地址:125.31.50.★
 谢谢赐教。受益匪浅

网友: 陈佳 时间:2008-06-30 13:06:49 IP地址:202.136.213.★
不错是不错 不过这个方法土了掉直接在FILTER 里判断不是更省事情?

网友: 陈佳 时间:2008-06-30 13:08:33 IP地址:202.136.213.★
还有如果你的 GET 和POST 不一致问题只要
 直接在TOMCAT 里有个SERVER.XML 的文件 在里面有个 encodeURI 的设置改下 UTF-8 就好了

网友: 本站网友 时间:2009-04-04 02:57:28 IP地址:218.19.61.★
太感谢了,看了你的博客,搞了一天一夜!终于搞定ajax中文问题了!


给我留言
版权所有 ChinaUnix.net 页面生成时间:0.12323