Servlet Send Image as Response
Advertisements
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>
Google Advertisment