Create the Servlet
- Right-click on the package you need it for and select New…
- From the new gallery select Web-Tier > Servlets on the left and on the right select HTTP Servlet
- Click Next and give the Servlet:
- Class name (ImageServlet)
- the Package it will reside in
- select doGet() method to implement
- click Next and set the Mapping details:
- Name: the name to use in the application
- Url pattern: the url path to use in jsp pages (/somePath)
- Finish
In the class, complete the method doGet() with what the servlet should do. If it is a DB query i.e.:
We need a connection to the DB to make a tranaction…
[java]
public static Connection getConnection() throws Exception {
String amDef = “bc.datamodel.common”;
String config = “ModelNameLocal”;
Connection con = null;
ApplicationModule am = null;
try {
am = Configuration.createRootApplicationModule(amDef, config);
con = ((DBTransactionImpl)am.getTransaction()).getPersistManagerConnection();
} finally {
Configuration.releaseRootApplicationModule(am, true);
}
return con;
}
[/java]
Then we need to fill-in the doGet() to do something i.e. extract an image from DB…
[java]
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
String empId = request.getParameter(“empId”);
OutputStream os = response.getOutputStream();
Connection conn = null;
try {
conn = this.getConnection();
PreparedStatement statement = conn.prepareStatement(“select get_emp_image(” + empId + “) as emp_image from dual”);
ResultSet rs = statement.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob(“emp_image”);
BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());
int b;
byte[] buffer = new byte[10240];
while ((b = in.read(buffer, 0, 10240)) != -1) {
os.write(buffer, 0, b);
}
os.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
[/java]
Plug the servlet reference to a JSP page to use:
[javascript]<af:objectImage source=”/ImageServlet?empId=#{bindings.EmpId}”/>[/javascript]
Adding the objectImage component of the ADF palette, will create an image object which will call the ImageServlet and pass the empId to it. The servlet will then activate the doGet() method and call the SQL statement within it to return the relevant data back to the JSP (the emp_image blob in our case).
Comments