Use JSP to read images from the database and display them on the webpage

Source: Internet
Author: User
Tags stmt tomcat

Environment mysql + tomcat:
<1> create the following table in mysql and insert the image.
The mysql. SQL file is as follows:
Create table photo (
Photo_no int (6) unsigned not null auto_increment,
Image blob,
Primary key ('photo _ no ')
)
<2> place show. jsp in any tomcat Directory. show. jsp: read blob from the database and generate image/jpg.
The show. jsp file is as follows:
<% @ Page contentType = "text/html; charset = gbk" %>
<% @ Page import = "java. io. *" %>
<% @ Page import = "java. SQL. *, javax. SQL. *" %>
<% @ Page import = "java. util. *" %>
<% @ Page import = "java. math. *" %>
<%
String photo_no = request. getParameter ("photo_no ");
// Mysql connection
Class. forName ("com. mysql. jdbc. Driver"). newInstance ();
String URL = "jdbc: mysql: // localhost: 3306/job? User = root & password = 111111 ";
Connection con = DriverManager. getConnection (URL );
// Oracle connection
// String URL = "jdbc: oracle: thin @ localhost: 1521: orcl2 ";
// User = "system ";
// Password = "manager ";
// Connection con = DriverManager. getConnection (URL, user, password );
Try {
// Prepare the statement execution object
Statement stmt = con. createStatement ();
String SQL = "SELECT * FROM PHOTO WHERE photo_no =" + photo_no;
ResultSet rs = stmt.exe cuteQuery (SQL );
If (rs. next ()){
Blob B = rs. getBlob ("photo_image ");
Long size = B. length ();
// Out. print (size );
Byte [] bs = B. getBytes (1, (int) size );
Response. setContentType ("image/jpeg ");
OutputStream outs = response. getOutputStream ();
Outs. write (bs );
Outs. flush ();
Rs. close ();
}
Else {
Rs. close ();
Response. sendRedirect ("./images/error.gif ");
}
}
Finally {
Con. close ();
}
%>
<3> place the following file in the same directory of show. jsp.
The index.html file is as follows:
<HTML>
<HEAD>
<TITLE> image testing </TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
<TD> image test </TD>
</TR>
<TR>
<TD> </TD>
</TR>
</TABLE>
</BODY>
</HTML>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.