从mysql数据库中检索图像并将其显示在html页面中

时间:2012-05-04 08:51:43

标签: java servlet-3.0

我只是想从数据库中检索图像并显示它。我写了以下代码:

    RetreiveImage.java

    import myconnection.ConnetionDefault;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RetreiveImage extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response)         throws         ServletException, IOException{
    PrintWriter out = response.getWriter();
    Connection con=null;
    String id=request.getParameter("id");
    try{
    con=ConnetionDefault.getConnection();
    ResultSet results = null;
    PreparedStatement ps = null;
    ps = con.prepareStatement("select picture from pic_229084519 where pic_id=?");
    ps.setString(1,id);
    results = ps.executeQuery();
    String imgLen="";
    if(results.next()){
    imgLen = results.getString(1);
    System.out.println(imgLen.length());


    int len = imgLen.length();
    byte [] rb = new byte[len];
    InputStream readImg = results.getBinaryStream(1);
    int index=readImg.read(rb, 0, len);
    System.out.println("index"+index);
    ConnetionDefault.close(results,ps,con);
    response.reset();
    response.setContentType("image/jpg");
    response.getOutputStream().write(rb,0,len);
    response.getOutputStream().flush();

    RequestDispatcher rd=request.getRequestDispatcher("gg.html");
    rd.forward(request,response);
    }
    } catch (Exception e){

    e.printStackTrace();
    }
    }
    }

    retImagel.html

    <html>
    <head>
    <title>Login</title>

    </head>  
    <body bgcolor="Gold">
    <center>

    <form action="ret.pic">
    <table>
    <tr><th>Namme</th><td><input type="text" name="id" size="3"/></td><td></td>

    <td><input type="submit" value="Get"></td><td><input type="reset"     value="Cancel"/></td></tr>
    </table>
    </form>

    </center>
    </body>
    </html>

    gg.html

    <html>
    <head>
     <title>Login</title>

    </head>  
    <body bgcolor="Gold">

    <img src="/ret.pic?id=${id}"/>
    </center>
    </body>
    </html>

我的问题是它在默认响应页面中显示图像。但我希望它在gg.html中我错了..请帮助我。

1 个答案:

答案 0 :(得分:0)

在web.xml中设置过滤器以调用servlet。

在您的gg.html页面上插入标记&lt; img“url to image过滤器可以交叉”&gt;