I got a scenario to show image from other website through servlet. I am sharing this piece of code. Icon is a servlet. If you pass any image link with parameter name 'url' then this servlet will read that image and it will print to servlet output stream

Here you need to have apache-commons-io java library to run this servlet.
  

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class Icon extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    public Icon() {
        super();
    }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String urlImage = request.getParameter("url");
  URL url;
     InputStream is = null;
     try {
      response.setContentType("image/png");
   url = new URL(urlImage);
         is = url.openStream(); 
         InputStreamReader br = new InputStreamReader(is);
         ServletOutputStream out = response.getOutputStream();
         out.write(IOUtils.toByteArray(is));
         out.flush();
         out.close();
     } catch (MalformedURLException mue) {
          mue.printStackTrace();
     } catch (IOException ioe) {
          ioe.printStackTrace();
     } finally {
         try {
             if (is != null) is.close();
         } catch (IOException ioe) {
         }
     }
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 }

}

2 comments:

  1. image link with parameter name 'url' then this servlet will read that image and it will print to servlet output stream. hostpapa coupon

    ReplyDelete
  2. فهي وفيرة في المجاري وأحواض الصرف الصحي وتتميز بقدرتها العالية على التكاثر والانتشار. يمكنك استخدام شركة لمكافحة الحشرات في الدمامشركة مكافحة حشرات
    شركة مكافحة النمل الابيض بالخبر
    شركة مكافحة حشرات بالخبر
    شركة رش مبيدات بالخبر

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts