0

Hey could anyone help me with my servlet which is meant to display images to my jsp page after grabbing them from the database. My image servlet below doesn't seem to be displaying the image in my browser at all, only a broken image icon:

@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) {
            }
        }
    }
}
}

The image in my jsp page looks like this:

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

And finally my database connector class from which the result set comes from is:

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

My web.xml looks like this too:

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

If anyone would know why the image is not being displayed i woud be thankful

adarshr
  • 61,315
  • 23
  • 138
  • 167
user1851487
  • 547
  • 5
  • 13
  • 28

2 Answers2

2

There are 2 potential problems.

  1. The image URL is wrong. Look in the HTTP traffic monitor of your webbrowser's developer toolset (press F12 in Chrome/IE9/Firebug and look at Net(work) section). The HTTP response code must be 2nn/3nn and not 404. The answer of adarshr covers that.

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

    See also:


  2. You're closing the DB connection before returning the result set, but still attempting to access the result set after that. This would throw a SQLException which should appear as a HTTP 500 error page. This should also be visible as such in HTTP traffic monitor or even when you specify the image's URL directly in browser's address bar.

    You need to rewrite your code that you don't return a ResultSet, but just return the image's content as byte[], or to move the DB job to inside the servlet. In any case, you should never ever create public methods which takes or returns a ResultSet instance.

    See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

Looks like the URL to the image servlet is wrong. If you start it with a /, it takes you to the root of the context.

<img src="${pageContext.request.contextPath}/Image/<%= h.getHomeID() %>">
adarshr
  • 61,315
  • 23
  • 138
  • 167