2

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> 

1 Answer 1

3

You're making a conceptual mistake here. In HTML, images are to be represented by <img> element with a src attribute which should point to the image's URL. This is in JSF represented by the <h:graphicImage> component whose value attribute will render the src attribute. It expects a String which 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.

<h:dataTable value="#{bean.images}" var="image"> <h:column><h:graphicImage value="images/#{image.id}" /></h:column> </h:dataTable> 

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 follows

String imageId = request.getPathInfo().substring(1); 

Finally use this identifier to get the content as InputStream from the DB and write it to the OutputStream of the response along a correct set of headers.

See also:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.