【问题标题】:How to retrieve image from database and display in JSP via Servlet? [duplicate]如何通过 Servlet 从数据库中检索图像并在 JSP 中显示? [复制]
【发布时间】:2011-09-13 00:38:50
【问题描述】:

我的 ImageDAO 如下所示:

public InputStream getPhotos(Long userid) throws 
  IllegalArgumentException, SQLException, ClassNotFoundException {

  Connection connection = null;
  PreparedStatement preparedStatement = null;
  ResultSet resultset = null;
  Database database = new Database();
  InputStream binaryStream = null;

  try {

    connection = database.openConnection();
    preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);                  
    preparedStatement.setLong(1, userid);
    preparedStatement.executeUpdate();

    while(resultset.next()) {
      binaryStream = resultset.getBinaryStream(4);
    }

  } catch (SQLException e) {
      throw new SQLException(e);
  } finally {
      close(connection, preparedStatement, resultset);
  }
  return binaryStream;
}

我的 ImageServlet 看起来像这样:

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

  // Getting user id from session
  HttpSession session = request.getSession(false);
  Long userid = (Long) session.getAttribute("user");    

  try {

      InputStream photoStream = imageDAO.getPhotos(userid);

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

      try {

      // Open streams
      input = new BufferedInputStream(photoStream, 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 {
          output.close();
          input.close();
      }

      //Redirect it to profile page
      RequestDispatcher rd = request.getRequestDispatcher
                            ("/webplugin/jsp/profile/photos.jsp");
      rd.forward(request, response);


  } catch (Exception e) {
      e.printStackTrace();
  }

}

我的 JSP 图片 src 应该是什么样子的

<img src="What to put here">

披露:

servlet 代码复制自此链接http://balusc.blogspot.com/2007/04/imageservlet.html

问题:

  1. 如何从 ImageServlet 检索 JSP 中的图像。 Stackoverflow 中有人说要放 &lt;img src="URL to Servlet" /&gt;。但我不明白这意味着什么。
  2. 上述方法是从数据库中检索图像的正确方法吗?或者有没有更好的方法。

编辑:我的 Web.xml 看起来像这样

<servlet>
  <servlet-name>Photo Module</servlet-name>
  <servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Photo Module</servlet-name>
  <url-pattern>/Photos</url-pattern>
</servlet-mapping>

【问题讨论】:

    标签: java image jsp servlets


    【解决方案1】:

    附上您的 web.xml 以查看您是如何(如果有的话)映射您的 servlet,以便我们可以为您提供 URL。

    web.xml 是将 URL 与 servlet 绑定的方式。

    您对 Servlet 输出流的缓冲输出的方式是恕我直言,这是一种将数据写入输出的正确且良好的方式。最好使用过滤器来缓存输出,而不是一直写响应。

    更新: 根据您提到的博客作为源代码和其中的 web.xml,正确的 url 应该是

    其中 my_image.jpg 是上传图片的示例名称。

    【讨论】:

    • 您能否解释一下过滤缓存如何帮助而不是总是写响应。这是我正在寻找的确切点。你能解释一下吗?
    【解决方案2】:

    如果您为模式/Photos注册您的 serlvet

    <img src="/yourContextRoot/Photos" />
    

    【讨论】:

      【解决方案3】:

      HTML &lt;img&gt; 元素的 src 应该只指向一个 URL。 URL 是一个网址,就像您在浏览器地址栏中输入的网址一样。 Servlet 可以通过web.xml 映射到特定的 URL 模式,因此当您调用与 servlet 映射匹配的 URL 时,将调用 servlet。另见our Servlets Wiki。

      您已将 servlet 映射到 URL 模式 /Photos。输入像

      这样的 URL

      http://localhost:8080/YourContextPath/Photos

      在浏览器地址栏中应该显示图像。所以基本上,假设 JSP 在相同的上下文路径中运行,应该这样做:

      <img src="Photos" />
      

      或者当你想让它相对于域根目录时,你需要动态地包含上下文路径:

      <img src="${pageContext.request.contextPath}/Photos" />
      

      也就是说,你的servlet有一些问题。您尚未设置内容类型标头。这样浏览器将不知道如何处理 HTTP 响应。当你直接在地址栏中输入它的 URL 时,它会显示一个 Save As 弹出窗口,当你在 &lt;img&gt; 中调用它时它会显示 nothing。如果是 JPG 图片,则在调用response.getOutputStream()之前添加以下行。

      response.setContentType("image/jpeg");
      

      这样浏览器就会知道它是 JPG 图片,并会以这种方式显示。另请参阅您链接的博客,了解设置标题的正确方法。

      另一个问题是您正在调用request.getSession(false),它可能会在无法进行会话时返回null。但是您没有在下一行检查它!所以要么使用

      HttpSession session = request.getSession();
      

      所以它永远不会是null,或者添加一个

      if (session == null) {
          // Display some default image or return a 404 instead.
          return;
      }
      

      您希望对userId 和photoStream 执行相同的操作。如果不存在,则显示默认图像或返回 404。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-27
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多