小编典典

如何从数据库检索图像并通过Servlet在JSP中显示?

jsp

我的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中的某人说要放 <img src="URL to Servlet" />。但是我没有什么意思。
  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>

阅读 253

收藏
2020-06-08

共1个答案

小编典典

src的HTML
<img>元素应该只是指向一个URL。URL是一个网址,就像您在浏览器地址栏中输入的网址一样。可以通过以下方式将Servlet映射到某些URL模式web.xml:当您调用与Servlet映射匹配的URL时,将调用Servlet。

您已将servlet映射到的URL模式/Photos。输入如下网址

http:// localhost:8080 / YourContextPath
/照片

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

<img src="Photos" />

或者,当您要使其相对于域根目录时,则需要动态包含上下文路径:

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

就是说,您的servlet中存在一些问题。您尚未设置内容类型标头。这样,浏览器将不知道如何处理HTTP响应。直接在地址栏中输入其URL时,它将显示“
另存为” 弹出窗口,而在中调用它时则不显示 任何 内容<img>。如果是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。

2020-06-08