Define ServletInputStream



The ServletInputStream Class

The ServletInputStream class extends InputStream. It is implemented by the server and provides an input stream that a servlet developer can use to read the data from a client request. It defines the default constructor. In addition, a method is provided to read bytes from the stream. Its signature is shown here:

int readLine(byte[] buffer, int offset, int size) throws IOException

Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or -1 if an end-of-stream condition is encountered.

Sample example by using ServletOutputStream Class are as follows:

Sample Ex-1:

import javax.servlet.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintWriter;

/**
*    A Test for readLine method
*/

public class ReadLineTestServlet extends GenericServlet {

public void service ( ServletRequest request, ServletResponse response ) throws ServletException, IOException {
PrintWriter out = response.getWriter();
ServletInputStream sins = request.getInputStream();

int contentLen = request.getContentLength();

if ( contentLen >= 1 ) {

byte buffer[] = new byte[ contentLen ];

int len = sins.readLine( buffer, 0, buffer.length );
String expectedResult = “ULTRA SPARC”;
//our client sent ULTRA SPARC  in the stream

String result = new String( buffer, 0, len );
if ( result.trim().equals( expectedResult ) ) {
out.println( “ReadLineTest test PASSED” );
} else {
out.println( “ReadLineTest test FAILED<BR>” );
out.println( “     ServletInputStream.readLine() returned incorrect result <BR>” );
out.println( “     Expected result = ” + expectedResult + ” <BR>” );
out.println( “     Actual result = |” + result + “| <BR>” );
}
} else {
out.println( “ReadLineTest test FAILED<BR>” );
out.println( “     ServletRequest.getContentLength() returned incorrect result <BR>” );
out.println( “     Expected a result >= 1 <BR>” );
out.println( “     Actual result = ” + contentLen + ” <BR>” );
}
}
}

Share with SociBook.com

Random Posts

Post a Comment