Here is my jsp code and my servlet code in getting an image
newJSP.jsp
<html>
<body>
<form action="newServlet" method="GET">
id <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!