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

a k*_*a k 0 java jsp servlets image

我的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;
}
Run Code Online (Sandbox Code Playgroud)

我的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();
  }

}
Run Code Online (Sandbox Code Playgroud)

我的JSP图像src应该怎么样

<img src="What to put here">
Run Code Online (Sandbox Code Playgroud)

披露:

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

问题:

  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>
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 6

src的HTML <img>元素应该只是指向一个URL.URL是您在浏览器地址栏中输入的网址.Servlet可以映射到某些URL模式,web.xml以便在调用与servlet映射匹配的URL时,将调用servlet.另请参阅我们的Servlets Wiki.

您已将servlet映射到URL模式/Photos.输入类似的URL

HTTP://本地主机:8080/YourContextPath /照片

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

<img src="Photos" />
Run Code Online (Sandbox Code Playgroud)

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

<img src="${pageContext.request.contextPath}/Photos" />
Run Code Online (Sandbox Code Playgroud)

说,你的servlet有一些问题.您尚未设置内容类型标头.这样浏览器就不知道如何处理HTTP响应.当您在地址栏中直接输入其URL时,它将显示" 另存为"弹出窗口,当您调用它时,它将不会显示任何内容<img>.如果是JPG图像,则调用之前添加以下行response.getOutputStream().

response.setContentType("image/jpeg");
Run Code Online (Sandbox Code Playgroud)

通过这种方式,浏览器可以理解它是JPG图像,并且它将显示它.另请参阅您为了设置标题的正确方法而链接的博客.

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

HttpSession session = request.getSession();
Run Code Online (Sandbox Code Playgroud)

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

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

你想为userId和做同样的事情photoStream.如果不存在,则显示默认图像或返回404.