Wednesday, May 7, 2014

Usage Of Servlets in ADF To Show Af:Image Based On a Parameter

Requirement : Show a Picture based on an Id which is coming from a service.

Solution : Create a Servlet in ViewController


Select appropriate methods to implement from doGet(), doPost(), service(), doPut(), doDelete().

In my case i had to implement the doGet() method to get the response from the servlet and show that on the jsff page.

The URL pattern will let you point to the appropriate Servlet from the page.

A java class something like this will get generated:

package client;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet1
  extends HttpServlet
{
  private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

  public void init(ServletConfig config)
    throws ServletException
  {
    super.init(config);
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Servlet1</title></head>");
    out.println("<body>");
    out.println("<p>The servlet has received a GET. This is the reply.</p>");
    out.println("</body></html>");
    out.close();
  }
}

Override the doGet() method as per the requirement :
In my case i pass an Id to a service and get the byte[] in response to it.
I need to convert it to a jpg file, so set the content type to "image/jpg".
Write that to the out response of the doGet() and we are done defining and implementing the Servlet.

For Ex :

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    if (request.getParameter("dsId") != null)
    {
      OutputStream out = null;
      try
      {
        /*
          Code to get the Id from the service, added a jar file to the ViewController which has the webservice proxy client
          */
               }
        if (imageByte != null)
        {
          response.setContentType("image/jpg");
          out = response.getOutputStream();
          out.write(imageByte);
          out.flush();
        }
      }
      catch (Exception ex)
      {
        ex.printStackTrace();
      }
      finally
      {
        if (out != null)
          out.close();
      }
    }
  }
}

On the page where the image has to be showed on the run time give the appropriate Servlet URL

For Ex:

<af:image source="/dsimageservlet?dsId=#{bindings.DistributorId.inputValue}" id="i12"
                            inlineStyle="height:150px; width:150px;"/>

The newly added servlet can be view in web.xml file in my case the name is DSImageServlet.


Thats it, run the page and view the servlet response on the page.



No comments:

Post a Comment