4. 网页中动态显示图片
接下来我们要编程从数据库中取出图片,其代码如下所示。
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="java.io.*"%>
<jsp:useBean id="conn" scope="page" class="dbconn.DBResult"/>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+
":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'testimageout.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
int id= Integer.parseInt(request.getParameter("picid"));
String sql = "select pic from p WHERE picid="+id;
ResultSet rs=conn.getResult(sql);
while(rs.next())
{
ServletOutputStream sout = response.getOutputStream();
//图片输出的输出流
InputStream in = rs.getBinaryStream(1);
byte b[] = new byte[0x7a120];
for(int i = in.read(b); i != -1;)
{
sout.write(b);
//将缓冲区的输入输出到页面
in.read(b);
}
sout.flush();
//输入完毕,清除缓冲
sout.close();
}
%>
</body>
</html> |
将此文件保存为testimageout.jsp文件。下一步要做的工作就是使用HTML标记:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="java.io.*"%>
<jsp:useBean id="conn" scope="page" class="dbconn.DBResult"/>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+
":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'lookpic.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
String sql = "select * from p";
ResultSet rs=conn.getResult(sql);
while(rs.next())
{
%>
<ccid_file values="testimageout" % />" width="100" height="100">
<br>
<%
}
rs.close();
%>
</body>
</html> |