2013-01-18 110 views
1

嗨,我已經嘗試下面這個非常有用嘖嘖這裏找到:圖片Servlet的圖像返回爲空

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

我下面的教程,試圖創建我的形象的servlet從數據庫中檢索圖像和在我的jsp頁面上顯示它的用戶。據我所知的代碼看起來不錯,但控制檯顯示我500內部錯誤,我的服務器控制檯表明我的形象變量爲空在這裏:

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和空?

幫助讚賞。

回答

2

問題和代碼建議它是實際上dataManager這是null。代碼的編寫方式是,如果image將永遠是null,那麼它只會返回404而不是具有NullPointerException的500。

您需要確保dataManager不是null,例如,通過在init()方法中實例化它,或者如果它是EJB,則將它注入爲@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

+0

嗨,謝謝你的回覆。我使用了一個int()方法來安裝dataManager。但是代碼現在在我的控制檯中在servlet的while循環中觸發了「Stream Closed」異常 – user1851487

+1

這實際上是一個你應該提出新問題的另一個問題:)但是,你需要替換'InputStream content'通過'byte [] content'並使用'ResultSet#getBytes()'獲得它。這基本上是由於關閉連接後'InputStream'不再可用。 – BalusC