a.sql.*; public class getphoto extends HttpServlet { private static final String CONTENT_TYPE = "image/jpeg"; /**Initialize global variables*/ public void init() throws ServletException { } /**Process the HTTP Get request*/ public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //在数据库中照片的ID String PHOTOID = null; try { PHOTOID = request.getParameter("photoid"); } catch(Exception e) { e.printStackTrace(); } //连接数据库,自定义的数据库连接池管理类 DBConnectionManager connMgr; connMgr = DBConnectionManager.getInstance(); Connection conn = connMgr.getConnection("comdb"); //属性文件中定义 //用来存储照片数据的缓冲区 byte [] buf=null; //扩展名可以从数据库得到,这里直接指定为JPEG String photoname="jpeg"; try{ //根据ID查找照片 String searchSql="select photo from employee where id ="+PHOTOID; Statement stmt = conn.createStatement(); ResultSet RS_photo = stmt.executeQuery(searchSql); //将图片数据读入缓冲区 if (RS_photo.next()){ buf = RS_photo.getBytes(1); }else { buf = new byte[0]; } }catch (Exception e){ //throw e; } finally { connMgr.freeConnection("comdb", conn); } //response.setContentType(CONTENT_TYPE); //告诉浏览器输出的是图片 response.setContentType("image/"+photoname); //图片输出的输出流 OutputStream out = response.getOutputStream(); //将缓冲区的输入输出到页面 out.write(buf); //输入完毕,清楚缓冲 out.flush(); } /**Clean up resources*/ public void destroy() { } } 编译后的Servlet getphoto.class也会自动放置在工程文件的WEB-INF下的classes目录下。 2.3 JSP实现数据库图文信息浏览 成功建立好Servlet后,下一步要做的工作就是将原先的HTML标记: <img src="../image/"+RS_photo.getString(photo_fiield) width="100" height="80">加以修改,替换为Servlet标记。即可以将下面的标记写于HTML或JSP中页面中 <img border="0" src="/servlet/getphoto?photoid=XXX&ts=AAAAA" > 其中XXX是图片的ID,AAAAA是时间戳,用来防止图片不刷新。如果我们要浏览数据库中的所有图文信息,可以加入适当的循环控制。在本文的示例WEB应用程序中作者加入了简单的表格控制来修饰输出的图文信息。详细的程序代码如下所示: ***************JSP页面浏览数据库图文信息代码************* <%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*"
errorPage="" %> <jsp:useBean id="comdbBean" scope="page" class="dbbean.conn"/> //使用javabean建立页面的数据连接 <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body> <% int table_num=4; //指定表格每行显示记录的条数 ResultSet RS_photo; strSQL="select * from employee"; RS_photo =comdbBean.executeQuery(strSQL); out.println("<table width=''75%'' border=''1''align=''center''>"); out.println("<tr>"); while(RS_photo.next()) { String pic01=rs.getString("id_stud"); pic01=""+pic01+""; String employeename=rs.getString("name"); //加入表格控制 out.println("<td>"); out.println("<div align=\"center\" 此新闻共有3页 上一页 1 2 3 下一页 |