如何将blob图像从数据库显示到jsp

时间:2016-01-26 13:09:04

标签: html jsp servlets

这是我的jsp代码和获取图像的servlet代码

newJSP.jsp

<html>
<body>
    <form action="newServlet" method="GET">
        id &nbsp;&nbsp;<input type="text" name="id"><br>
        <input type="submit">
    </form>
</body>

newServlet

@WebServlet("/image/*")

public class newServlet扩展了HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    LReceiptsDAO lrDAO = new LReceiptsDAO();
    // Get ID from request.
    int imageId = Integer.parseInt(request.getParameter("id"));

    // Check if ID is supplied to the request.
    if (imageId == 0) {
        // Do your thing if the ID is not supplied to the request.
        // Throw an exception, or send 404, or show default/warning image, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Lookup Image by ImageId in database.
    // Do your "SELECT * FROM Image WHERE ImageID" thing.
    byte[] image = lrDAO.getReceiptFile(imageId);

    // Check if image is actually retrieved from database.
    if (image == null) {
        // Do your thing if the image does not exist in database.
        // Throw an exception, or send 404, or show default/warning image, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Init servlet response.
    response.reset();
    response.setContentType("image/*");
    response.setContentLength(image.length);

    // Write image content to response.
    response.getOutputStream().write(image);
}

}

我不知道如何在另一个jsp文件中显示图像内容。有没有办法可以重定向到新的jsp并通过这段代码显示它:

ServletContext context = getServletContext();
        request.setAttribute("ca", c);
        request.setAttribute("bList", bList);
        RequestDispatcher dispatch = context.getRequestDispatcher("/Accounting_CashAdvance_PrepareVoucher.jsp");
        dispatch.forward(request, response);  

我感谢那些将回答我的问题的人。谢谢!

1 个答案:

答案 0 :(得分:1)

采用新的JSP。 在Body中,只需放置img标签。

<html>
<body>

<img src="/image"/>

</body>
</html>