Use JSP to read pictures from the database and display them on the Web page

Source: Internet
Author: User
Tags mysql stmt tomcat
js| Data | database | Web page | show

Environment Mysql+tomcat:

<1> first set up the following table under MySQL. and insert the image.

Mysql.sql files are as follows:

CREATE TABLE Photo (
Photo_no Int (6) unsigned not NULL auto_increment,
Image blob,
PRIMARY KEY (' Photo_no ')
)

<2> put show.jsp in any directory of Tomcat. show.jsp function: To read a blob from a database and produce image/jpg.

show.jsp files are 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 statement execution Object
Statement stmt = con.createstatement ();

String sql = "SELECT * from PHOTO WHERE photo_no =" + photo_no;
ResultSet rs = stmt.executequery (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> put the following files in the same directory as show.jsp.

index.html files are as follows:

<HTML>
<HEAD>
<TITLE> Image Testing </TITLE>

</HEAD>

<BODY>
<TABLE>
<TR>
<TD> Image Testing </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.