1

嗨,我已尝试遵循此处找到的这个非常有用的 tut:

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?

帮助表示赞赏。

4

1 回答 1

2

问题和代码表明它实际上是. 代码的编写方式是,如果曾经是,那么它只会返回 404,而不是 500 和.dataManagernullimagenullNullPointerException

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


与具体问题无关DatabaseConnector,作为static变量并将 JDBCConnection声明为实例变量也不是一个好兆头。此代码不是线程安全的。从这里开始学习如何编写正确的 JDBC 代码:在多线程系统中使用静态 java.sql.Connection 实例是否安全?在您找到图像 servlet 的同一博客上,您还可以找到基本的JDBC DAO 教程

于 2013-01-18T12:10:45.083 回答