Servlet Send Image as Response

Advertisements

Prev Tutorial Next Tutorial

Send Image as Response in Servlet

To Send an image as response from servlet back to the browser the following changes are required.

  • Set MIME type or content type as image by using image/.gif.
  • To transfer image response, you need ServletOutputStream as an outputStream to write the response. In this case printWriter class is not suitable.
  • Use an image encoder class, to store that image file into the outputStream object.

Example

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
import java.awt.image;
import javax.swing.imageIcon.*;  
import Acme.JpmEncoders.GifEncoder;  

public class MyServlet extends HttpServlet
{  
  
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  {  
  
    response.setContentType("image/gif");  
    ServletOutputStream out = response.outputStream();  
            
    // optain image icon
	ImageIcon imageicon=new ImageIcon("c:/cow.gif");

	// encoding the image and send to the outputStream

	GifEncoder g=new GifEncoder(image, out)

	g.encode();
    out.close();
  }  
} 

In the above servlet program you have need to use third party class called GifEncoder, so you need a jar file to set in the classpath called acme.jar

To compile the above servlet you need the flowing jar files.

  • servlet-api.jar
  • acme.jar

You need to copy acme.jar file into the lib folder to execute above servlet program

web.xml

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>MyServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>s1</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  

</web-app>  

Prev Tutorial Next Tutorial

Advertisements

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements