简体   繁体   English

如何使用Java Servlet从JSP中的数据库显示图像?

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

Here is my current servlet code. 这是我当前的servlet代码。 This is where I will get the image from the database. 这是我将从数据库中获取图像的地方。

newServlet.java 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 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. 我从此链接获得了servlet代码,但是在设置init servlet响应部分时似乎出现了错误。

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. 这是我第一次尝试从数据库中获取图像斑点,并通过DAO和servlet获得它,到目前为止,我只看到在jsp中包含Java代码的代码。

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. 找不到getContentType()getContent()方法的原因是因为它们不存在。 The type of the variable image is byte[] - an array of primitive bytes - and arrays don't have those methods. 可变image的类型为byte[] -原始字节数组-数组没有这些方法。 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[] . 您获得该代码的链接的image变量类型为com.example.model.Image (在该示例中已定义并具有那些方法的类),而不是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. 顺便说一句,您示例中的代码选择了一个名为receipt_filepath的字段,该字段建议该字段将映像的路径存储在磁盘上,而不是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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