如何使用java servlet在JSP中显示数据库中的图像?

时间:2016-01-26 10:41:35

标签: java jsp servlets dao

这是我当前的servlet代码。这是我从数据库中获取图像的地方。

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

我从这个link获得了servlet代码,但是当我设置init servlet响应部分时,我似乎遇到了错误。

我很抱歉提出这个问题。这是我第一次尝试从数据库中获取图像blob并通过DAO和servlet获取它,到目前为止,我只看到了包含jsp中java代码的代码。

我很感激帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

尝试替换

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

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

答案 1 :(得分:0)

找不到getContentType()getContent()方法的原因是因为它们不存在。变量image的类型是byte[] - 一个原始字节数组 - 而数组没有这些方法。该代码实际上不应该编译。

您获得该代码的链接的image变量类型为com.example.model.Image(已在该示例中定义且具有这些方法的类)而不是byte[]

顺便提一下,示例中的代码是选择一个名为receipt_filepath的字段,该字段表示该字段存储磁盘上图像的路径,而不是blob。如果是这样,您应该解析该路径并从磁盘读取该文件(如您链接到的示例中所做的那样)。

如果是blob,那么你真的应该将图像的内容类型存储在数据库中。在这种情况下,你可以这样做:

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);
...

然后:

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