简体   繁体   中英

How to display an image from a database in a JSP using a java servlet?

Here is my current servlet code. This is where I will get the image from the database.

newServlet.java

package LAWS_SERVLETS;

import LAWS_DAOS.LReceiptsDAO;
import LAWS_ENTITIES.Lawyer_Receipt;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Meryl
 */
@WebServlet(name = "newServlet", urlPatterns = {"/newServlet"})
public class newServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

    }

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        LReceiptsDAO lrDAO = new LReceiptsDAO();
        int imageId = Integer.parseInt(request.getParameter("id"));

        // Check if ID is supplied to the request.
        if (imageId == 0) {

            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }


        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.getContentType());
        response.setContentLength(image.getContent().length);

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

    }


}

LReceiptsDAO

public byte[] getReceiptFile(int id){
   byte[] l = null;

    try {

        DBConnectionFactory myFactory = DBConnectionFactory.getInstance();
        Connection conn = myFactory.getConnection();
        PreparedStatement pstmt = conn.prepareStatement("SELECT receipt_filepath FROM  lawyer_receipts"
                + "where lawyerreceipt_id = ? ");

        pstmt.setInt(1, id);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){

          l = rs.getBytes("receipt_filepath");              
        }
         conn.close();
         return l;
    } catch (SQLException ex) {
        Logger.getLogger(LReceiptsDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

I got the servlet code from this link but it seems that I get an error when I set the init servlet response part.

I'm very sorry for asking this question. It's my first time trying to get image blobs from the database and getting it via a DAO and a servlet and so far, I only saw codes that included the java codes in a jsp.

I appreciate the help. Thank you!

try replace

response.setContentType(image.getContentType());
response.setContentLength(image.getContent().length);
response.getOutputStream().write(image.getContent());

to

response.setContentType("image/*");
response.setContentLength(image.length);
response.getOutputStream().write(image);

The reason the getContentType() and getContent() methods aren't found is because they don't exist. The type of the variable image is byte[] - an array of primitive bytes - and arrays don't have those methods. That code shouldn't actually compile.

The link where you got that code has the type of image variable as com.example.model.Image (a class which has been defined in that example and has those methods) not byte[] .

Incidentally, the code in your example is selecting a field called receipt_filepath which suggests that the field stores the path to the image on disk, not a blob. If so, you should resolve that path and read the file from disk (as is done in the example you linked to).

If it is a blob, then you really should be storing the content type of the image in the database, too. In that case, you can do something like this:

PreparedStatement pstmt = conn.prepareStatement("SELECT image_blob_field_name, image_content_type_field_name FROM  lawyer_receipts"
            + "where lawyerreceipt_id = ? ");
...
byte[] image = rs.getBytes(1);
String contentType = rs.getString(2);
...

Then later:

response.setContentType(contentType);
response.setContentLength(image.length);
response.getOutputStream().write(image);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM