如何在JSP页面中检索和显示数据库中的图像?

oyjwcjzk  于 2022-12-25  发布在  其他
关注(0)|答案(6)|浏览(178)

如何在JSP页面中从数据库中检索和显示图像?

pod7payv

pod7payv1#

让我们分步骤看看应该发生什么:

  • JSP基本上是一种视图技术,它应该生成HTML输出。
  • 要以HTML格式显示图像,需要HTML <img>元素。
  • 要让它定位图像,需要指定其src属性。
  • src属性需要指向一个有效的http:// URL,而不是本地磁盘文件系统路径file://,因为当服务器和客户端在物理上不同的机器上运行时,src将永远无法工作。
  • 图像URL需要在请求路径(例如http://example.com/context/images/foo.png)或作为请求参数(例如http://example.com/context/images?id=1)中具有图像标识符。
  • 在JSP/Servlet世界中,您可以让Servlet侦听特定的URL模式(如/images/*),这样您就可以在特定的URL上执行一些Java代码。
  • 映像是二进制数据,可以从DB中以byte[]InputStream的形式获取,JDBC API为此提供了ResultSet#getBytes()ResultSet#getBinaryStream(),JPA API为此提供了@Lob
  • 在Servlet中,您可以按照通常的Java IO方式将byte[]InputStream写入响应的OutputStream
  • 需要指示客户端将数据作为映像处理,因此至少需要设置Content-Type响应头。您可以通过ServletContext#getMimeType()基于映像文件扩展名获得正确的响应头,您可以通过web.xml中的<mime-mapping>扩展和/或覆盖映像文件扩展名。

应该是这样的,它几乎可以自己编写代码,让我们从HTML(在JSP中)开始:

<img src="${pageContext.request.contextPath}/images/foo.png">
<img src="${pageContext.request.contextPath}/images/bar.png">
<img src="${pageContext.request.contextPath}/images/baz.png">

如有必要,您还可以在使用JSTL进行迭代的同时使用EL动态设置src

<c:forEach items="${imagenames}" var="imagename">
    <img src="${pageContext.request.contextPath}/images/${imagename}">
</c:forEach>

然后定义/创建一个servlet,它侦听URL模式为/images/*的GET请求,下面的示例使用普通JDBC执行该作业:

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {

    // content=blob, name=varchar(255) UNIQUE.
    private static final String SQL_FIND = "SELECT content FROM Image WHERE name = ?";

    @Resource(name="jdbc/yourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
    private DataSource dataSource;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String imageName = request.getPathInfo().substring(1); // Returns "foo.png".

        try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_FIND)) {
            statement.setString(1, imageName);
            
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    byte[] content = resultSet.getBytes("content");
                    response.setContentType(getServletContext().getMimeType(imageName));
                    response.setContentLength(content.length);
                    response.getOutputStream().write(content);
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
                }
            }
        } catch (SQLException e) {
            throw new ServletException("Something failed at SQL/DB level.", e);
        }
    }

}

如果您担心HEAD和缓存头文件以及正确响应这些请求,请使用这个抽象模板作为静态资源servlet。

另请参见:

2fjabf4q

2fjabf4q2#

我建议你把它当作两个问题来处理。有几个问题和答案与这两个问题都相关。
1.如何从MySQL加载blob
例如,请参见Retrieve image stored as blob
1.如何动态显示图像
请参见例如动态显示缩略图

lsmepo6l

lsmepo6l3#

我已经用Oracle数据库编写并配置了JSP中的代码。希望能有所帮助。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class displayfetchimage
 */
@WebServlet("/displayfetchimage")
public class displayfetchimage extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public displayfetchimage() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        Statement stmt = null;
        String sql = null;
        BufferedInputStream bin = null;
        BufferedOutputStream bout = null;
        InputStream in = null;

        response.setContentType("image/jpeg");
        ServletOutputStream out;
        out = response.getOutputStream();
        Connection conn = employee.DbConnection.getDatabaseConnection();
        HttpSession session = (HttpSession) request.getSession();
        String ID = session.getAttribute("userId").toString().toLowerCase();
        try {
            stmt = conn.createStatement();
            sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
            ResultSet result = stmt.executeQuery(sql);
            if (result.next()) {
                in = result.getBinaryStream(1);// Since my data was in first column of table.
            }
            bin = new BufferedInputStream(in);
            bout = new BufferedOutputStream(out);
            int ch = 0;
            while ((ch = bin.read()) != -1) {
                bout.write(ch);
            }

        } catch (SQLException ex) {
            Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bin != null)
                    bin.close();
                if (in != null)
                    in.close();
                if (bout != null)
                    bout.close();
                if (out != null)
                    out.close();
                if (conn != null)
                    conn.close();
            } catch (IOException | SQLException ex) {
                System.out.println("Error : " + ex.getMessage());
            }
        }

    }

    // response.getWriter().append("Served at: ").append(request.getContextPath());
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Statement stmt = null;
        String sql = null;
        BufferedInputStream bin = null;
        BufferedOutputStream bout = null;
        InputStream in = null;

        response.setContentType("image/jpeg");
        ServletOutputStream out;
        out = response.getOutputStream();
        Connection conn = employee.DbConnection.getDatabaseConnection();
        HttpSession session = (HttpSession) request.getSession();
        String ID = session.getAttribute("userId").toString().toLowerCase();
        try {
            stmt = conn.createStatement();
            sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
            ResultSet result = stmt.executeQuery(sql);
            if (result.next()) {
                in = result.getBinaryStream(1);
            }
            bin = new BufferedInputStream(in);
            bout = new BufferedOutputStream(out);
            int ch = 0;
            while ((ch = bin.read()) != -1) {
                bout.write(ch);
            }

        } catch (SQLException ex) {
            Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bin != null)
                    bin.close();
                if (in != null)
                    in.close();
                if (bout != null)
                    bout.close();
                if (out != null)
                    out.close();
                if (conn != null)
                    conn.close();
            } catch (IOException | SQLException ex) {
                System.out.println("Error : " + ex.getMessage());
            }
        }

    }

}
3lxsmp7m

3lxsmp7m4#

如果输出流未显示,请尝试刷新并关闭它。Blob image = rs.getBlob(ImageColName);InputStream in = image.getBinaryStream();//将blob输出到HttpServletResponse response.setContentType("image/jpeg");BufferedOutputStream o = new BufferedOutputStream(response.getOutputStream());

byte by[] = new byte[32768];
    int index = in.read(by, 0, 32768);
    while (index != -1) {
        o.write(by, 0, index);
        index = in.read(by, 0, 32768);
    }
    o.flush();
    o.close();
vdgimpew

vdgimpew5#

我使用了SQL SERVER数据库,所以答案的代码是一致的。您所要做的就是在jsp页面中包含一个<img>标记,并从其src属性调用servlet,如下所示

<img width="200" height="180" src="DisplayImage?ID=1">

这里1是图像在数据库中的唯一ID,ID是一个变量。我们在servlet中接收这个变量的值。在servlet代码中,我们从表中正确的列中获取二进制流输入。这就是你的图像存储在哪一列中。在我的代码中,我使用第三列,因为我的图像作为二进制数据存储在第三列中。从表中检索输入流数据后,我们在输出流中读取其内容,以便将其写入屏幕。

import java.io.*;  
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;  
import javax.servlet.http.*;  
import model.ConnectionManager;
public class DisplayImage extends HttpServlet { 
    public void doGet(HttpServletRequest request,HttpServletResponse response)  
             throws IOException  
    { 
    Statement stmt=null;
    String sql=null;
    BufferedInputStream bin=null;
    BufferedOutputStream bout=null;
    InputStream in =null;

    response.setContentType("image/jpeg");  
    ServletOutputStream out;  
    out = response.getOutputStream();  
    Connection conn = ConnectionManager.getConnection();

    int ID = Integer.parseInt(request.getParameter("ID"));
        try {
            stmt = conn.createStatement();
            sql = "SELECT * FROM IMAGETABLE WHERE ID="+ID+"";
            ResultSet result = stmt.executeQuery(sql);
            if(result.next()){
                in=result.getBinaryStream(3);//Since my data was in third column of table.
            }
            bin = new BufferedInputStream(in);  
            bout = new BufferedOutputStream(out);  
            int ch=0;   
            while((ch=bin.read())!=-1)  
                {  
                bout.write(ch);  
            }  

        } catch (SQLException ex) {
            Logger.getLogger(DisplayImage.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
        try{
            if(bin!=null)bin.close();  
            if(in!=null)in.close();  
            if(bout!=null)bout.close();  
            if(out!=null)out.close();
            if(conn!=null)conn.close();
        }catch(IOException | SQLException ex){
            System.out.println("Error : "+ex.getMessage());
        }
    }

    }  
}

执行完jsp或html文件后,您将在屏幕上看到图像。

camsedfj

camsedfj6#

您还可以创建自定义标记来显示图像。
1)创建自定义标签java类和tld文件。
2)编写逻辑以显示图像,如通过Base64将byte[]转换为string。
因此,无论您在单个JSP页面中只显示一个图像还是显示多个图像,它都用于每个图像。

相关问题