java - 图像 Servlet 图像返回 null

标签 java sql image oracle servlets

嗨,我尝试遵循这里找到的这个非常有用的图解:

http://balusc.blogspot.co.uk/2007/04/imageservlet.html

我正在按照教程尝试创建我的图像 servlet,它从数据库检索图像并将其显示在我的 jsp 页面上的用户。据我所知,代码看起来没问题,但控制台向我显示 500 内部错误,并且我的服务器控制台指示我的 Image 变量在这里为空:

Image image = dataManager.getPhotos(homeId);

下面是我的完整代码:

@WebServlet(name = "ImageServlet", urlPatterns = {"/Image"})
public class ImageServlet extends HttpServlet {

private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private static DatabaseConnector dataManager;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Get ID from request.
    String homeId = request.getParameter("id");

    // Check if ID is supplied to the request.
    if (homeId == null) {
        // 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;
    }
    try {
        // Lookup Image by ImageId in database.
        // Do your "SELECT * FROM Image WHERE ImageID" thing.
        Image image = dataManager.getPhotos(homeId);

        // 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.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType("image/png");
        response.setHeader("Content-Length", String.valueOf(image.getLength()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + image.getHomeID() + "\"");

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            // Open streams.
            input = new BufferedInputStream(image.getContent(), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } finally {
            // Gently close streams.
            close(output);
            close(input);
        }

    } catch (IllegalArgumentException ex) {
        Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private static void close(Closeable resource) {
    if (resource != null) {
        try {
            resource.close();
        } catch (IOException e) {
            // Do your thing with the exception. Print it, log it or mail it.
            e.printStackTrace();
        }
    }
}

下面的我的数据库连接器处理和检索以下数据:

 public Image getPhotos(String homeID) throws
        IllegalArgumentException, SQLException, ClassNotFoundException {

    createConnection();

    Image img = new Image();

    ResultSet rs = null;
    PreparedStatement preparedStatement = null;

    String strQuery = "SELECT * "
            + "FROM home_photo "
            + "WHERE home_photo.home_id = ?";

    try {
        preparedStatement = conn.prepareStatement(strQuery);
        preparedStatement.setString(1, homeID);
        rs = preparedStatement.executeQuery();

        while (rs.next()) {
            img.setHomeID(rs.getInt("home_id"));
            img.setPhotoID(rs.getInt("photo_id"));
            img.setContent(rs.getBinaryStream("photo"));
            img.setDescription(rs.getString("description"));
            img.setLength(rs.getInt("length"));
            img.setContentType(rs.getString("type"));
        }

    } catch (SQLException e) {
        throw new SQLException(e);
    }

    closeConnection();
    return img;
}

其中我看不到它会在哪里返回 img 和 null?

感谢帮助。

最佳答案

问题和代码表明实际上dataManager,它是null。代码的编写方式是,如果 imagenull,那么它只会返回 404,而不是带有 NullPointerException 的 500 >.

您需要确保dataManager不为null,例如通过在 init() 方法中实例化它,或者如果它是 EJB,则通过将其注入(inject)为 @EJB

<小时/>

与具体问题无关DatabaseConnector 是一个 static 变量,而 JDBC Connection 被声明为实例变量也不是一个好兆头。这段代码不是线程安全的。从这里开始学习如何编写正确的 JDBC 代码:Is it safe to use a static java.sql.Connection instance in a multithreaded system?在您找到图像 servlet 的同一个博客上,您还可以找到基本的 JDBC DAO tutorial .

关于java - 图像 Servlet 图像返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14398650/

相关文章:

sql - postgres - 如何根据两个数组的 AND 填充一个新数组

mysql - SQL-如何将一个值从一个表插入另一个表,但另一表中的数据应保持不变

python - 在背景图像上叠加散点图并更改轴范围

java - 如何为交互式 session 创建有状态的 Groovy 绑定(bind)

Java 定时器 : how to select + what are the limitations?

MySQL无法应用外键约束

css - Angular 4 - 以 45 度为步长旋转图像

c# - 如何在 C# 中旋转图像 x 度?

java - 使用字符串和基数 2 - 36 进行 BaseConversion

java - 从InputStream中获取字节数组