Acquiring text stream for response

We can send text data as response by using PrintWriter object.ServletResponse interface defines getWriter() method to get PrintWriter Object
public PrintWriter getWriter() throws IOException
Example: PrintWriter out=resp.getWriter();

Acquiring binary stream for response

we can get this object by using getOutputStream() method of ServletResponse.
public ServletOutputStream os=resp.getOutputStream()

Example:

  1. Create servlet that extends HttpServlet
  2. Create web.xml
  3. Create war file and deploy web application
  4. Output of web application
  5. Download web application

Create servlet that extends HttpServlet

package com.java2learn;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DisplayImage extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		resp.setContentType("image/png");
		ServletOutputStream os = resp.getOutputStream();
		String path = getServletContext().getRealPath("image.PNG");
		File f = new File(path);
		FileInputStream fis = new FileInputStream(f);
		byte[] b = new byte[(int) f.length()];
		//Reading the image and placing into byte array.
		fis.read(b);
		//Write byte array to the response.
		os.write(b);
		os.flush();
		os.close();

	}

}

Create web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>WebApp</display-name>

	<servlet>
		<servlet-name>DisplayImage</servlet-name>
		<servlet-class>com.java2learn.DisplayImage</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>DisplayImage</servlet-name>
		<url-pattern>/imageServlet</url-pattern>
	</servlet-mapping>

</web-app>

Final application structure

FinalApplicationImage

Create war file and deploy the application

Output:
outputImage

Download Project: WebApp

Note:
We can get either PrintWriter object or ServletOutputStream object but not both simlteniously,violation leads to RuntimeException saying IllegalStateException.
Example

public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
  PrintWriter out=resp.getWriter();
  ServletOutputStream os=resp.getOutputStream();
}

RuntimeException:IllegalStateException.getWriter() has already been called for this response