Define ServletOutputStream
By Ramakrishna on Aug 25, 2008 in Servlet Tutorial
The ServletOutputStream Class
The ServletOutputStream class extends OutputStream.It is implemented by the server and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is define.It also defines the print() and println() method, which output data to the stream
Sample example by using ServletOutputStream Class are as follows:
sample1;Example Using the jsp servletoutputstream
package com.ack.web.servlet;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
* In the ServletOutputStream all methods converge on the write(int)
* output method. So it is this method that we override to customise
* what is sent back to an HTTP client that uses the JSPServletOutputStream.
*
* In this case we simply replace ‘<’ with ‘[' and '>' with ']‘, each
* with ascii values 60, 91, 62, 93 respectively.
*
*/
public class JSPServletOutputStream extends ServletOutputStream {
private HttpServletResponse delegate;
public JSPServletOutputStream( HttpServletResponse hss ) {
delegate = hss;
}
public void write( int c ) throws IOException {
if( c == 60 ) {
delegate.getOutputStream().write( 91 );
}
else if( c == 62 ) {
delegate.getOutputStream().write( 93 );
}
else {
delegate.getOutputStream().write( c );
}
}
}
sample 2:Example Using the servletoutputstream in servlet program
import javax.servlet.*;
import javax.servlet.ServletOutputStream;
import java.io.*;
public class FileDownloadServlet extends HttpServlet {
public void doGet ( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
String docSid = null;
String fullName = null;
String name = null;
ServletOutputStream out = res.getOutputStream ( ) ;
String fullName = “fileToBeDownloaded.xxx”;
String pathName = getServletContext ( ) .getRealPath ( “/” + fullName ) ;
String contentType = getServletContext ( ) .getMimeType ( pathName ) ;
if ( contentType != null )
res.setContentType ( contentType ) ;
else
res.setContentType ( “application/octet-stream” ) ;
res.setHeader ( “Content-Disposition”, “attachment; filename=\”" + name + “\”" ) ;
FileInputStream fis = null;
// Return the file
try {
fis = new FileInputStream ( fullName ) ;
byte [ ] buf = new byte [ 4 * 1024 ] ; // 4K buffer
int bytesRead;
while ( ( bytesRead = fis.read ( buf ) ) != -1 )
out.write ( buf, 0, bytesRead ) ;
}
catch ( FileNotFoundException e ) {
out.println ( “File not found: ” + fullName ) ;
}
catch ( IOException e ) {
out.println ( “Problem sending file ” + pathName + “: ” + e.getMessage ( ) ) ;
}
finally {
if ( fis != null )
fis.close ( ) ;
}
}
}
