HttpServletRequest#getReader()在GlassFish 4中为空

时间:2013-07-18 14:00:40

标签: servlets glassfish-4

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

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

}

0 个答案:

没有答案