如何从数据库中检索图像并通过Servlet在JSP中显示? [英] How to retrieve image from database and display in JSP via Servlet?

查看:98
本文介绍了如何从数据库中检索图像并通过Servlet在JSP中显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

My ImageDAO如下所示:

My ImageDAO looks like this:

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如下所示:

My ImageServlet looks like this:

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图像应如何看待喜欢

How should my JSP image src look like

<img src="What to put here">

披露:

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

The servlet code is copied from this link http://balusc.blogspot.com/2007/04/imageservlet.html

问题:


  1. 如何从JSP中检索图像ImageServlet。 Stackoverflow中的某个人说要把
    < img src =URL到Servlet/> 。但我不是这意味着什么。

  2. 上述方法是否正确地从数据库中检索图像?或者有更好的方法。

  1. How to retreive image in JSP from ImageServlet. Someone in Stackoverflow said to put <img src="URL to Servlet" />. But I don't what it means.
  2. Is the above method correct way to retreive image from database? Or is there better way.

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

My Web.xml looks like this

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


推荐答案

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

The src of the HTML <img> element should just point to an URL. An URL is a web address like as the one you enter in your browser address bar. Servlets can be mapped on certain URL patterns by web.xml so that when you invoke an URL which matches the servlet mapping, that the servlet will be invoked. See also our Servlets Wiki.

您已映射servlet在 /照片的网址格式上。输入网址

You have mapped the servlet on an URL pattern of /Photos. Entering an URL like


浏览器地址栏中的http:// localhost:8080 / YourContextPath / Photos

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

in the browser address bar should display the image. So basically, assuming that the JSP runs in the same context path, this should do:

<img src="Photos" />

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

Or when you want to make it relative to the domain root, then you need to include the context path dynamically:

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






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


Said that, there are some problems in your servlet. You haven't set the content type header. This way the browser won't know what to do with the HTTP response. It'll display a Save As popup when you enter its URL straight in address bar and it'll display nothing when you call it in <img>. If it's a JPG image, then add the following line before you call response.getOutputStream().

response.setContentType("image/jpeg");

这样浏览器就会知道它是JPG图像并且它会显示它。另请参阅您为正确设置标题的方式链接的博客。

This way the browser understands that it's a JPG image and it'll display it as such. See also the blog which you linked for the proper way of setting the headers.

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

Another problem is that you're calling request.getSession(false) which can potentially return null when there's no means of a session. But you are not checking for that on the next line! So either use

HttpSession session = request.getSession();

因此它永远不会 null ,或者添加

so that it is never null, or add a

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

你想对 userId <做同样的事情/ code>和 photoStream 。如果不存在,则显示默认图像或返回404。

You would like to do the same for userId and photoStream. If it's absent, then display a default image or return a 404.

这篇关于如何从数据库中检索图像并通过Servlet在JSP中显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆