图像Servlet无法正常工作

时间:2013-01-17 15:57:00

标签: java jsp servlets

嘿,任何人都可以帮助我使用我的servlet,这是为了在从数据库中获取图像后将图像显示到我的jsp页面。我的图像servlet似乎根本没有在我的浏览器中显示图像,只有一个损坏的图像图标:

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

private DatabaseConnector dataManager;
BufferedInputStream input = null;
BufferedOutputStream output = null;

@Override
public void init() {
    dataManager = new DatabaseConnector();
}

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Prepare.
    String name = request.getPathInfo().substring(1); // Returns "foo.gif". You may want to do nullchecks here to avoid NPE's.
    ResultSet resultSet = null;

    try {
        // Query DB.
        resultSet = dataManager.getPhotos(1);

        if (resultSet.next()) {
            // Image found, prepare response and send it.
            response.setContentType(resultSet.getString("contentType"));
            response.setContentLength(resultSet.getInt("contentLength"));
            response.setHeader("Content-Disposition", "inline;filename=\"" + name + "\"");
            input = null;
            output = null;

            try {
                input = new BufferedInputStream(resultSet.getBinaryStream("content"));
                output = new BufferedOutputStream(response.getOutputStream());
                byte[] buffer = new byte[1024];

                for (int length; (length = input.read(buffer)) > -1;) {
                    output.write(buffer, 0, length);
                }
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException logOrIgnore) {
                    }
                }
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException logOrIgnore) {
                    }
                }
            }
        } else {
            // No image found, send HTTP 404.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException e) {
        throw new ServletException("Something failed at SQL/DB level.", e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException logOrIgnore) {
            }
        }
    }
}
}

我的jsp页面中的图像如下所示:

<img src="/Image/<%= h.getHomeID() %>">

最后,结果集来自的数据库连接器类是:

public ResultSet getPhotos(String photoID) throws
        IllegalArgumentException, SQLException, ClassNotFoundException {

    createConnection();


    ResultSet rs = null;
    PreparedStatement preparedStatement = null;

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

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

    } catch (SQLException e) {
        throw new SQLException(e);
    } finally {
        closeConnection();
        return rs;
    }
}

我的web.xml也是这样的:

<servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>DB.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/Image/*</url-pattern>
</servlet-mapping>

如果有人知道为什么没有显示图像,我会感激不尽

2 个答案:

答案 0 :(得分:2)

有两个潜在的问题。

  1. 图片网址错误。查看webbrowser开发人员工具集的HTTP流量监视器(按Chrome / IE9 / Firebug中的F12,然后查看 Net(工作)部分)。 HTTP响应代码必须是2nn / 3nn而不是404. adarshr的答案涵盖了这一点。

    <img src="${pageContext.request.contextPath}/Image/<%= h.getHomeID() %>">
    

    另见:


  2. 您在返回结果集之前关闭了数据库连接,但仍然在此之后尝试访问结果集。这将抛出SQLException,它应该显示为HTTP 500错误页面。这也应该在HTTP流量监视器中可见,或者甚至直接在浏览器的地址栏中指定图像的URL。

    您需要重写不返回ResultSet的代码,只需将图像的内容返回为byte[],或者将数据库作业移动到servlet内部。在任何情况下,您都不应该创建获取或返回ResultSet实例的公共方法。

    另见:

答案 1 :(得分:1)

看起来图片servlet的URL错误。如果您使用/启动它,它会将您带到上下文的根目录。

<img src="${pageContext.request.contextPath}/Image/<%= h.getHomeID() %>">
相关问题