0

Here is my jsp code and my servlet code in getting an image

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 extends 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);
}

}

I do not know how to show the image content in another jsp file . Is there a way that I can redirect to the new jsp and show it there thru this code:

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

I appreciate those who will be answering my question. Thank you!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user3418987
  • 137
  • 2
  • 7
  • 16
  • Does your servlet work when you call it directly? It seems to me the content type is supposed to be specific - `image/jpeg`,`image/gif`, `image/png`, etc. – RealSkeptic Jan 26 '16 at 13:16

1 Answers1

1

Take a new JSP. In Body, Just place the img tag.

<html>
<body>

<img src="/image"/>

</body>
</html>