2

我正在一个项目中工作。我试图从使用以下代码创建的会话中获取用户名:-

获取当前用户信息.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();

        }
    }
}

调用.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”实际上我的用户名仅 s@s.com。

4

1 回答 1

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");

相关文章:从 servlet 下载文件客户端时出现意外字符

更新

还有一些我在原始答案中忘记的东西。将响应对象的 ContentTyoe 设置为 text/plain 因为您实际上是在返回纯文本字符

response.setContentType("text/plain");
于 2012-09-03T07:10:45.223 回答