954,574 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Displaying an image and its attributes in JSP

Hello to all. I'm using the following jsp to display an image from a mysql database.

<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>

<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/people";
 
ResultSet rs = null;
PreparedStatement psmnt = null;
InputStream sImage;

try {
 
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "123");
 
psmnt = connection.prepareStatement("SELECT pic FROM person WHERE id = ?");
psmnt.setString(1, "9"); 
rs = psmnt.executeQuery();

%>



<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
       
<%
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}//End of while
}//End of if

%>
<p>
    This is some text.
</p>

<%}
catch(Exception ex){
out.println("error :"+ex);
}
finally {
// close all the connections.
rs.close();
psmnt.close();
connection.close();
}
%>
    </body>
</html>


And thus far it seems to work, well sort of. The problem here is that I can't get the text I put in the h1 and p tags to show. Another problem I'm having is that whenever I try to display another attribute of the the table (like the name of the image) I get an error which says "getOutputStream() has already been called for this response ". Is there a way I can display the image and the html? as well as the other attributes of the image?

Any suggestions will be greatly appreciated. Thanks in advance.

CodeBoy101
Junior Poster in Training
71 posts since Dec 2007
Reputation Points: 8
Solved Threads: 0
 

Hello CodeBoy101,
1. I don't think this code compiles because i don't see where you declared a "out" object for the following code.

catch(Exception ex){
out.println("error :"+ex);
}

2. This is just a gues, but maybe you need to create an object of the output stream, like this:

outputStream.getOutputStream();
while((size=sImage.read(bytearray))!= -1 ){
response.outputStream.write(bytearray,0,size);
}//End of while

But i'm not too sure about any of these. Hope it helps ) .

Alex_
Junior Poster
175 posts since Jun 2008
Reputation Points: 10
Solved Threads: 3
 

Alex_,
out - out is an intrinsic page object.

__avd
Posting Genius (adatapost)
Moderator
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You