3

我在 GlassFish 4 下遇到了一个奇怪的问题。我正在将 POST 请求中的原始数据(使用 jQuery)发送到 servlet。由于阅读器为空(立即返回-1),通过 request.getReader() 读取 doPost 中的数据失败。但是,如果我更改代码:

Reader reader = request.getReader();

至:

BufferedReader reader = new BufferedReader( new InputStreamReader( request.getInputStream() ) );

是成功。请注意,使用 Tomcat 6,7 或 Jetty 时 request.getReader() 不为空。有谁知道 GlassFish 4 有什么问题?这是一个完整的简单片段来演示该问题:

package test.servlet;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

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

public class TestServlet extends HttpServlet {

  @Override
  protected void doGet( HttpServletRequest request, HttpServletResponse response )
    throws ServletException, IOException
  {
    writeInitialPage( response );
  }

  @Override
  protected void doPost( HttpServletRequest request,
                         HttpServletResponse response )
    throws ServletException, IOException
  {
    writeData( response, readData( request ) );
  }

  private void writeData( HttpServletResponse response, String data ) throws IOException {
    Writer writer = response.getWriter();
    for( int i = 0; i < data.length(); i++ ) {
      writer.write( data.charAt( i ) );
    }
  }

  private String readData( HttpServletRequest request ) throws IOException {
    Reader reader = request.getReader();
//    BufferedReader reader = new BufferedReader( new InputStreamReader( request.getInputStream() ) );
    StringBuilder buffer = new StringBuilder();
    int current = reader.read();
    while( current != -1 ) {
      char ch = ( char )current ;
      buffer.append( ch );
      current = reader.read();
    }
    reader.close();
    return buffer.toString();
  }

  private void writeInitialPage( HttpServletResponse response ) throws IOException {
    Writer writer = response.getWriter();
    writer.write( "<html>" );
    writer.write( "<head>" );
    writer.write( "<script type=\"text/JavaScript\" src=\"/test/js/jquery-1.10.2.min.js\"></script>" );
    writer.write( "</head>" );
    writer.write( "<body>" );
    writer.write( "<button type=\"button\" onclick=\"" );
    writer.write( "$.ajax('/test/test',{" );
    writer.write( "'data': 'data1 data2 data3 data4 data5 data6 data7 data8 data9 data10'," );
    writer.write( "'type': 'POST'," );
    writer.write( "'processData': false," );
    writer.write( "'contentType': 'text/plain'" );
    writer.write( "});" );
    writer.write( "\">Send</button>" );
    writer.write( "</body>" );
    writer.write( "</html>" );
  }

}
4

0 回答 0