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.

Recommended Answers

All 2 Replies

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_,
out - out is an intrinsic page object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.