I’m using following code for reading images from database but when i call getter method of pb in h:datatable value to display images on jsf page i got the error “oracle.sql.BLOB cannot be cast to java.lang.String”.Any idea please?
Java class is having pb property.
Java code for reading image:
public List<ImageBean> getPb() throws Exception {
int i = 0;
List<ImageBean> pb= new ArrayList<ImageBean>();
String url = "jdbc:oracle:thin:@localhost:1521:globldb3";
String username = "scott";
String password = "tiger";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT name,image FROM save_image";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet resultSet = pstmt.executeQuery();
while (resultSet.next()) {
String n =resultSet.getString(1);
File image = new File("D:\\java3.JPG");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(2);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
pb.add(i,new ImageBean(n,resultSet.getBlob(2)));
i++;
fos.close();
}
conn.close();
return pb;0
}
JSF page:-
<h:dataTable styleClass="panelGridColums" value="#{tableBean.pb}" var="i" border="1" >
<h:column>
<f:facet name="header">Id</f:facet>
<h:graphicImage value="#{i.pimage}" />
</h:column>
</h:dataTable>
You’re making a conceptual mistake here. In HTML, images are to be represented by
<img>element with asrcattribute which should point to the image’s URL. This is in JSF represented by the<h:graphicImage>component whosevalueattribute will render thesrcattribute. It expects aStringwhich in turn represents the image’s URL. It does not expect some blob, nor a byte array.You basically need a servlet here. You should let the image’s URL point to that servlet along with the image identifier as request parameter or pathinfo and let the servlet stream the image’s content from the DB to the response.
E.g.
where the
#{image.id}returns the unique image identifier. In a servlet which is mapped on an URL pattern of/images/*you can then get it as followsFinally use this identifier to get the content as
InputStreamfrom the DB and write it to theOutputStreamof the response along a correct set of headers.See also: