How to solve the problem of JSP Image Display

Source: Internet
Author: User

Premise: use JSP to display images. The image is stored in the database.

Method: connect to the database using JDBC, read data from the database, and output data to the page using the output stream.

<% @ Page contentType = "text/html" language = "java" %>
<% @ Page buffer = "16kb" %>
<% @ Page import = "java. SQL. *" %>
<% @ Page import = "java. io. *" %>
<% Int len = 10*1024*1024;
Class. forName ("oracle. jdbc. driver. OracleDriver"). newInstance ();
String url = "jdbc: oracle: thin: @ 10.168.99: 1521: orafy"; // orcl: SID of your database String user = "lhzy ";
String password = "qwertyuiop ";
Connection conn = DriverManager. getConnection (url, user, password );
Statement stmt = conn. createStatement (ResultSet. TYPE_SCROLL_SENSITIVE, ResultSet. CONCUR_UPDATABLE );
String SQL = "select pic from test ";
ResultSet rs1_stmt.exe cuteQuery (SQL); // locate the rs. next () record ();
InputStream in = rs. getBinaryStream (1); // ①
Response. reset (); // return the marked position in the stream
Response. setContentType ("image/jpg"); // or gif // get the input stream
OutputStream toClient = response. getOutputStream (); // ②
Byte [] P_Buf = new byte [len];
Int I;
While (I = in. read (P_Buf ))! =-1)
{
ToClient. write (P_Buf, 0, I );
} In. close ();
ToClient. flush (); // force clear the buffer
ToClient. close (); // ②
%>
<% Rs. close ();
Stmt. close ();
Conn. close (); %>

Note:

There are two aspects to note: ① the code at the place should be noted that the next () function should be called before recording, and the first record should be located, the index of the column in the record starts from 1, not from 0. ② If an error occurs, check whether the write stream is disabled. Is the following sentence. The possible cause is that response. getOutputStread () is also called elsewhere (). If this function is not disabled, the call cannot be successful.

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.