2012-09-03 67 views
2

我正在一個項目中工作。在這我試圖用下面的代碼創建得到會話的用戶名: -爲什麼我得到responseText(從Servlet通過Ajax的JavaScript)與額外的字符?

GetCurrentUserInfo.java

package servlet; 

import java.io.IOException; 
import java.io.ObjectOutputStream; 
import java.io.OutputStream; 
import java.util.Vector; 

import javax.servlet.ServletConfig; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

public class GetCurrentUserInfo extends HttpServlet 
{ 

    ServletContext contx = null; 
    public void init(ServletConfig config) throws ServletException 
    { 
     contx = config.getServletContext(); 
    } 

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
    { 
     try 
     { 
      OutputStream outer = res.getOutputStream(); 
      ObjectOutputStream oos = new ObjectOutputStream(outer); 
      String userName = (String) req.getSession().getAttribute("username"); 
      oos.writeChars(userName); 
      oos.flush(); 
      oos.close(); 
     } 

     catch (Throwable e) 
     { 
      e.printStackTrace(); 

     } 
    } 
} 

Calling.js

function getUserInfo() 
{ 
    var userInfoHttp; 
    if (window.XMLHttpRequest) 
    { 
     userInfoHttp = new XMLHttpRequest() 
    } 
    else if (window.ActiveXObject) 
    { 
     userInfoHttp = new ActiveXObject("Microsoft.XMLHTTP") 
    } 
    userInfoHttp.open("POST", "GetCurrentUserInfo", false); 
    userInfoHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    userInfoHttp.onreadystatechange = function() 
    { 
     if (userInfoHttp.readyState == 4) 
     { 
      if (userInfoHttp.status == 200) 
      { 
       var res = TrimString(userInfoHttp.responseText); 
       alert(res); 
      } 
     } 
    } 
    userInfoHttp.send(null); 
    isAnnotationUpdate = false; 

} 

我水庫我得到用戶名與一些額外的字符,如下所示: - 「 w s @ s . c o m」 實際上,我的用戶名僅爲[email protected]

回答

0

我認爲兩件事情可以解決您的編碼問題

首先使用使用OutputStreamWriter,並給它編碼值

OutputStream stream = response.getOutputStream(); 
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8"); 
String userName=(String)req.getSession().getAttribute("username"); 
writer.write(userName); 
writer.flush(); 

,然後確保你的回答有正確的編碼

response.setCharacterEncoding("UTF-8"); 

相關文章:Unexpected character when downloading file client side from a servlet

更新

和其他東西我忘了原來的答案。將響應對象的ContentTyoe設置爲文本/純文本,因爲您實際上正在返回純文本字符

response.setContentType("text/plain"); 
+0

什麼是第三行? – Shanky

相關問題