JSP字符串变量中显示的未知字符。

时间:2011-11-22 06:35:56

标签: jsp

我在JSP中使用String变量来获取windows中的登录名 虽然它在浏览器中正确显示 当字符串作为值传递给文本框时,会显示未知字符?? 如何摆脱它?这是我使用btw的代码

<

%
  String username=null,remoteHost=null;
String auth = request.getHeader("Authorization");
if (auth == null)
{
  response.setStatus(response.SC_UNAUTHORIZED);
  response.setHeader("WWW-Authenticate", "NTLM");
  response.flushBuffer();
  return;
}
if (auth.startsWith("NTLM "))
{
  byte[] msg = new sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
  int off = 0, length, offset;
  if (msg[8] == 1)
  {
    byte z = 0;
    byte[] msg1 = {(byte)'N', (byte)'T', (byte)'L', (byte)'M', (byte)'S', (byte)'S', (byte)'P', z,(byte)2, z, z, z, z, z, z, z,(byte)40, z, z, z, (byte)1, (byte)130, z, z,z, (byte)2, (byte)2, (byte)2, z, z, z, z, z, z, z, z, z, z, z, z};
    response.setHeader("WWW-Authenticate", "NTLM " + new sun.misc.BASE64Encoder().encodeBuffer(msg1));
    response.sendError(response.SC_UNAUTHORIZED);
    return;
  }
  else if (msg[8] == 3)
  {
    off = 30;

    length = msg[off+17]*256 + msg[off+16];
    offset = msg[off+19]*256 + msg[off+18];
    remoteHost = new String(msg, offset, length);

    length = msg[off+1]*256 + msg[off];
    offset = msg[off+3]*256 + msg[off+2];
    String domain = new String(msg, offset, length);

    length = msg[off+9]*256 + msg[off+8];
    offset = msg[off+11]*256 + msg[off+10];
    username = new String(msg, offset, length);

    out.println("<h2>Welcome:"+username+"</h2><BR>");
    //out.println("RemoteHost:"+remoteHost+"<BR>");
    //out.println("Domain:"+domain+"<BR>");
  }
}
%>           

1 个答案:

答案 0 :(得分:0)

NTLM身份验证方案alledgedly requires,使用UTF-16LE为字符串3消息编码字符串。您依靠默认字符集来解码字节,而不是显式指定要使用的字符集。别!平台可以使用任何默认字符集。

你真的应该添加一个Charset参数:

String username=null,remoteHost=null;
String auth = request.getHeader("Authorization");
Charset charset = Charset.forName("UTF-16LE");
/* ... */
{
    off = 30;

    length = msg[off+17]*256 + msg[off+16];
    offset = msg[off+19]*256 + msg[off+18];
    remoteHost = new String(msg, offset, length, charset);

    /* ... use ascii for every other string you build
     * that should be ASCII-encoded according to the
     * NTLM Authentication Scheme...
     */

确保以任何JSP的方式导入java.nio.charset.Charset


也就是说,您可能希望将解码后的字节数组的原始内容转储到某处(使用toString中的java.util.Arrays),这样您就可以确保输入是正确的。没有这些信息,没有什么可以去的。