我想在JSP页面的MySQL表中显示一个blob(图像),我的代码如下:
<%
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
byte[ ] imgData = null ;
String DRIVER= "com.mysql.jdbc.Driver";
String databaseName = "imd";
String connectionUrl = "jdbc:mysql://127.0.0.1:3306/" + databaseName;
String DB_USER = "root";
String DB_PASSWD = "root";
try{
Class.forName(DRIVER);
con = DriverManager.getConnection(connectionUrl,DB_USER,DB_PASSWD);
stmt = con.createStatement();
rs = stmt.executeQuery("select SiteKey from imd_user_sitekey where userName = 'lili'");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
} else {
out.println("Display Blob Example");
out.println("image not found for given id>");
return;
}
response.setContentType("image/gif");
OutputStream out = response.getOutputStream();
out.write(imgData);
out.flush();
oout.close();
}catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
<h1>Hello, <%= message %>, Please enter your password!</h1>
<br/>
<html:form action="sitekey">
<bean:message key="label.password"/>
<html:password property="password"></html:password>
<html:submit/>
</html:form>
图片可以成功显示,但其他内容低于&lt; %%&gt;我的JSP页面中的代码没有显示出来,整个页面就像一张图片一样。有人可以帮我解决这个问题吗? 非常感谢你!
答案 0 :(得分:0)
这是因为你设置了response.setContentType("image/gif");
。要在页面中显示HTMl,JSP页面内容类型必须为response.setContentType("text/html");
答案 1 :(得分:0)
这段代码可以帮助你....这是我的show_image.jsp
<%
String id="1250";
session.setAttribute("num", id);
%>
<body>
<image src="display.jsp" border="0" height="200px" width="200px"/>
<h1>Hello, Please enter your password!</h1>
<br/>
<html:form action="sitekey">
<bean:message key="label.password"/>
<html:password property="password"></html:password>
<html:submit/>
</html:form>
</body>
这里我通过dispaly.jsp文件外部引用图像
<% Blob image = null;
String no=(String)session.getAttribute("num");
byte[ ] imgData = null ;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection); DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("select photo from file1 where id = '"+no+"'");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
} else {
out.println("Display Blob Example");
out.println("image not found for given id");
return;
}
// display the image
response.setContentType("image/gif");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
} catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
} finally {
try {
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e);
e.printStackTrace();
}
}
%>